How to solve ValueError: could not convert string to float

ValueError: could not convert string to float shows up when you try to convert the string object to float. But the string object contains invalid floating characters such as commas, text, special characters, etc.

Firstly, let’s understand what causes this error in detail.

What causes ValueError: could not convert string to float?

In real-time, the input files are in TXT,CSV, or XML format. The data from these files are treated as strings. Even the numerical data is considered as a string. To convert these number-like strings to float, we can use the float() method.

float() constructs a floating-point number from the given string. If any invalid characters are found in the string, the above error is thrown.

The string can contain, “+“,”“,numbers,”.”,”nan“,”e” values. Refer to Python’s Official Guide on the float() for more details. If the string contains any other characters, an error is seen.

Example 1: 

In some cases, the values for some fields will be missing, returning an empty string. When you try to convert an empty string to a floating-point number, an error is seen.

final_price=""
print(f"The final price is",float(final_price))

Output:

Traceback (most recent call last):
  File "C:\Users\paian\PycharmProjects\PythonHowTo\venv\Solutions\value error.py", line 11, in <module>
    print(f"The final price is",float(final_price))
ValueError: could not convert string to float: ''

 

Example 2: 

cost_price="$945.67"
print("Cost price is", float(cost_price))

Output:

Traceback (most recent call last):
File "C:\Users\paian\PycharmProjects\PythonHowTo\venv\Solutions\value error.py", line 2, in <module>
print("Cost price is", float(cost_price))
ValueError: could not convert string to float: '$945.67'

Explanation: We see an error as the string contains $, which is an invalid floating point character.

 

Example 3: 

selling_price ="1,200"
print("Selling price is",float(selling_price))

Output:

Traceback (most recent call last):
  File "C:\Users\paian\PycharmProjects\PythonHowTo\venv\Solutions\value error.py", line 5, in <module>
    print("Selling price is",float(selling_price))
ValueError: could not convert string to float: '1,200'

Explanation: We see an error here, as there is a comma between the numbers.

 

Example 4: 

id="1OO4"
print("the id is",float(id))

Output:

Traceback (most recent call last):
  File "C:\Users\paian\PycharmProjects\PythonHowTo\venv\Solutions\value error.py", line 8, in <module>
    print("the id is",float(id))
ValueError: could not convert string to float: '1OO4'

Explanation: Although the string looks like a number, it is not. It contains the alphabet O, which looks similar to 0(zero).

 

Example 5:

final_price="11 .12"
print("The final price is {}",float(final_price))

Output:

Traceback (most recent call last):
File "C:\Users\paian\PycharmProjects\PythonHowTo\venv\Solutions\value error.py", line 11, in <module>
print(f"The final price is",float(final_price))
ValueError: could not convert string to float: '11 .12'

Explanation: In some systems, spaces are given in between the numbers to improve readability. When you try to convert such strings, a value error is seen as space is considered an invalid character in floating-point numbers.

 

To fix this error, ensure that the:

  • The string is not empty.
  • The string doesn’t contain text.
  • The string doesn’t contain commas.
  • The string doesn’t contain special characters(currency symbols).
  • The string doesn’t contain spaces in-between numbers. Note that ” 11.12″ or “11.12 ” doesn’t throw an error. However, “11 .12” does.

 

Fix 1: Check and Remove the invalid characters from the string

If you are expecting some invalid characters in the input, make sure to correct the string before calling the float() function. You can do so by having a check and correcting the string as shown below.

 

#check if dollar is present, if yes, then replace dollar with null character
cost_price="$945.67"
if "$" in cost_price:
    cost_price=cost_price.replace('$','')
print("Cost price is", float(cost_price))

#check if there is a comma, if present replace comman with null character.
selling_price ="1,200"
if "," in selling_price:
    selling_price=selling_price.replace(',','')
print("Selling price is ",float(selling_price))

#if the value is empty, convert it to a nan value
final_price=""
if final_price=="":
    final_price="nan"
print("The final price is",float(final_price))

# Remove if there any spaces, before calling the float()
final_price="11. 12"
if " " in final_price:
    final_price=final_price.replace(" ","")
print("The final price is",float(final_price))

Output:

Cost price is 945.67
Selling price is  1200.0
The final price is nan
The final price is 11.12

 

Fix 2: Use the Try-Except block for handling the errors.

As seen in Example 4, at times, text characters are present in the strings. In such cases, it is best to notify where the error lies.

id = "1OO4"
try:
    print("the id is", float(id))
except ValueError:
    print("The string %s contains invalid characters" %id)

Output:

The string 1OO4 contains invalid characters

Instead of throwing an error, we display a message indicating the error.

Conclusion

This brings us to the end of this article. We’ve seen different cases of seeing this error and discussed possible solutions to fix the ValueError: could not convert string to float.

We hope this article has been informative. Thanks for reading.

If you enjoyed reading, share this article.

Anusha Pai is a Software Engineer having a long experience in the IT industry and having a passion to write. She has a keen interest in writing Python Errorfixes, Solutions, and Tutorials.

1 thought on “How to solve ValueError: could not convert string to float”

Leave a Comment