Python ValueError: could not convert string to float

If you convert a string object into a floating-point in Python many times you will get a ValueError: could not convert string to float. Usually, this happens if the string object has an invalid floating value with spaces or comma Python will throw ValueError while parsing into string object into float.

In this article, we will take a look at what this error means and how to fix this error in your code with examples.

ValueError: could not convert string to float

If we are reading and processing the data from excel or CSV, we get the numbers in the form of a string, and in the code, we need to convert from string to float

Python has a built-in float() method that can parse the string to a floating-point number. This method will be useful when we need to perform a mathematical operation on a string object.

The float() method only allows you to convert strings that hold float-like numbers. This means that you cannot convert a value if 

  • A value contains spaces
  • A value contains a comma
  • A value contains special characters 

Exception could not convert string to float

order_value = '12,000'
tax_percentage = 4

tax_amount = (float(order_value)*(tax_percentage / 100))
print("The total tax amount is ", tax_amount)

Output

Traceback (most recent call last):
  File "c:/Projects/Tryouts/main.py", line 4, in <module>
    tax_amount = (float(order_value)*(tax_percentage / 100))
ValueError: could not convert string to float: '12,000'

Let’s take a simple example to demonstrate the ValueError exception. In the below code, we have the total order value in terms of USD, and we are accepting this in string format and performing a tax calculation.

If you see the above code, the order value has a comma-separated numeric value, and while parsing into a float, Python will throw ValueError: could not convert string to float.

There are a few other scenarios where you could get ValueError.

  1. Converting an empty string into a floating-point number
  2. Converting a non-floating string to a floating-point number

Fix ValueError: could not convert string to float

There are multiple ways to resolve the issue. Let’s take a look at each of the solutions.

Solution 1: Ensure the string has a valid floating value

The easiest way is to clean up the data or pass it in the correct format if we already know the data format before converting it into float. 

If the value has a comma, space, or any special characters, then it needs to be processed before converting into float. 

In the below code, we are storing a valid float number as a string, and later we are converting that into floating-point to calculate tax.

Example:

order_value = '12000'
tax_percentage = 4

tax_amount = (float(order_value)*(tax_percentage / 100))
print("The total tax amount is ", tax_amount)

Output

The total tax amount is  480.0

Solution 2: Use try-except

The best way is to handle the exception in case of an invalid data format. In the below code, it will run the code in the try block. If the conversion fails, then it runs the except block code.

Example:

order_value = '12,000'
tax_percentage = 4

try:
    tax_amount = (float(order_value)*(tax_percentage / 100))
    print("The total tax amount is ", tax_amount)
except:
    print ("Order value is invalid")

Output

Order value is invalid
Leave a Reply

Your email address will not be published. Required fields are marked *

Sign Up for Our Newsletters

Get notified of the best deals on our WordPress themes.

You May Also Like
List of Python free ebooks

List of Free Python Books

Table of Contents Hide Python SuccinctlyPython Data Science HandbookThink Python 2nd EditionAutomate the Boring Stuff with PythonMaking Games with Python & PygameData Structures and Algorithms in Python Google Python Style GuideA…
View Post