How to convert string with comma to float in Python?

In this Python tutorial, we will see how to convert strings with commas to float in Python using different methods with demonstrative examples.

Firstly we will see how to convert the string into float in Python with examples, we will also see where we will the problem occur while converting the string with commas into float in Python.

How to convert string to float Python

Yes, We can convert the data types in Python, one of them is converting string data type to float data type.

Let’s see how to convert string to float in Python.

In this example, we will use the built-in float() function to convert string to float in Python.

Example:

str = '15.456'
f = float(str)
print('Float Value =', f)

You can refer to the screenshot below to see the output for converting string to float Python.

python string to float with comma
How to convert string to float Python

The above code we can use to convert string to float in Python. But what if we try to convert the string with commas into the float. Lets see the problem.

Convert string with commas into float in Python

Large numbers are often represented with commas to make them easier to read.

For example, one million is commonly written as 1,000,000. If we attempt to convert this string to a float in Python with commas without any manipulation, an error will occur, as the standard float() function in Python does not handle commas.

million = '1,000,000'
print(type(million))

after_converting = float(million)
print(type(after_converting))

The output is:

Traceback (most recent call last):
  File "C:\Users\USER\PycharmProjects\pythonProject\TS\main.py", line 4, in <module>
    after_converting = float(million)
                       ^^^^^^^^^^^^^^
ValueError: could not convert string to float: '1,000,000'
<class 'str'>
Convert string with commas to float in Python showing error

The Error occur when we tried to convert the string with commas into a float in Python. as Python Float data type cannot hold comma as a value. So to convert these:

READ:  Python Nested Dictionary to JSON

There are different methods to convert strings with commas to float in Python without any error.

Removing commas from the Python string

To convert the string with commas to a float in Python, we need to first remove the commas from the string, then only we can convert the strings with commas into float data types in Python using the float() function.

There are three different methods to remove commas from a string in Python. They are:

  • Naive Method- using for loop with conditional statement
  • replace() string function
  • split() and join() Method

We will use these methods to remove commas and then, convert those strings to float in Python.

Remove commas from the Python string to float with commas using the naive method

In the naive method, we will use for loop in Python to loop over the string and will remove the commas using conditional statements, and then we will convert that string(without commas) into float using the float() function.

For example, suppose we are developing a financial application where we are given the price of a stock in a Python string format with commas (in USD). We need to convert this into float to perform financial computations.

stock_price = "2,999.99"
stock_price_float = ""

for x in stock_price:
    if x == ',':
        continue
    else:
        stock_price_float += x

stock_price_float = float(stock_price_float)

print(stock_price_float)
print(type(stock_price_float))

Here, we first created an empty string in Python and then had to loop over the string with commas, apply the conditional statement to remove the commas, and then convert the resultant string into a float in Python.

The output is:

2999.99
<class 'float'>
Python string to float with comma using Naive method

This way, we can use the Naive method to convert string with comma to float in Python.

READ:  How to fix the Python 3 pickle typeerror a bytes-like object is required not 'str'

Remove commas from the Python string to float with commas using the replace() string function

The first step is to remove the commas from the string. Python’s replace() string function can be used for this. The Python replace() string function replaces all occurrences of a specified value with another value. After removing the commas, we can now safely convert string with commas to float Python using Python’s float() function.

For example, We have a bank statement with us where the account balance is shown in the terms of a Python String. To do mathematical calculations we need to convert this data into a float value.

Account_balance = '1,085,555.22'

Account_balance = Account_balance.replace(",", "")
Account_balance_float = float(Account_balance)

print(Account_balance_float)
print(type(Account_balance_float))

The Output is:

1085555.22
<class 'float'>
Python convert string with comma to float using replace() method

What if we are having a Python list with string values with commas and we have to convert them into a float to do some mathematical operation in Python?

For example, We are working on a data analysis project where we have a Python list of the population of different cities in the US, in string format with commas. You need to convert these into float to perform arithmetic operations in Python.

population_list = ["8,398,748", "3,990,456", "2,716,450"]

# convert to float
population_list = [float(pop.replace(",", "")) for pop in population_list]

print(population_list)

The output is:

[8398748.0, 3990456.0, 2716450.0]
string to float python with comma in a list using replace() method

This way we can use the replace() string function in Python to convert the string to float with commas.

Remove commas from the Python string to float with commas using the split() and join() method

We can use a combination of the split() and join() string methods in Python to remove the commas before conversion.

READ:  How to Copy Elements from One List to Another in Python [6 Methods]

The split(“,”) method splits the original string into a list of strings in Python, breaking at each comma. Then, “”.join() concatenates these strings in Python back together, effectively removing the commas. Now without commas, this string can be converted into a Python float using the float() function.

For instance, we have a amount to pay to a store but the amount is written in a form of a Python string. we have to do some mathematical operations with that amount in Python. so we need to convert that value into the form of a Python float.

amount = "1,000,000"

amount_no_commas = "".join(amount.split(","))
amount_float = float(amount_no_commas)

print(amount_float)

The output is:

1000000.0
Python string with comma to float using split and join method

This way, we can convert Python string with commas to float using the split() and join() methods.

Conclusion

This tutorial specifically explored how to convert strings with commas into float numbers in Python.

We have seen three primary methods: using the Naive method, using the replace() string function, and combining the split() and join() string methods. Each method has its own applications and can be chosen based on the specific requirements of our program.

You may also like to read: