How to Convert a String to a Float in Python?

In this tutorial, I will explain how to convert a string to a float in Python. As a developer working on a project for a US-based company, I encountered a situation where I needed to convert user input (a string) into a floating-point number for further calculations. I will share my findings and provide a detailed example.

Convert a String to a Float in Python

Let us see how to convert a string to a float in Python.

Read How to Remove Spaces from String in Python?

Use float() Method

Python provides a built-in function called float() that allows you to convert a string to a float. Here’s how you can use it:

income_str = "45000.50"
income_float = float(income_str)
print(income_float) 

Output:

45000.5

In the screenshot below you can see the executed example code with the output.

Convert a String to a Float in Python

In this example, we have a string "45000.5" representing the annual income of a user from New York. By passing this string to the float() function, we convert it to a floating-point number, which is then stored in the income_float variable.

Check out How to Fix the “TypeError: string indices must be integers Error” in Python?

Handle Invalid Inputs

When working with user inputs, it’s crucial to handle potential errors gracefully. What if the user enters an invalid input that cannot be converted to a float? Let’s see how we can handle such cases:

try:
    income_str = "45,000.50"  # Invalid input with comma separator
    income_float = float(income_str)
    print(income_float)
except ValueError:
    print("Invalid input. Please enter a valid number.")

Output:

Invalid input. Please enter a valid number.

In the screenshot below you can see the executed example code with the output.

How to Convert a String to a Float in Python

In this example, the user input "45,000.50" contains a comma separator, which is not a valid format for float conversion. The float() function raises a ValueError exception. By using a try-except block, we catch this exception and print an appropriate error message to the user.

Read How to Insert a Character into a String at a Specific Index in Python?

Handle Different Number Formats

In the United States, numbers are often represented with comma separators for thousands and a dot for the decimal point. However, the float() function expects the input to be in a specific format. To handle different number formats, we can use the replace() method to preprocess the string before conversion:

income_str = "1,234,567.89"  # US number format
income_str = income_str.replace(",", "")  # Remove comma separators
income_float = float(income_str)
print(income_float) 

Output:

1234567.89

In the screenshot below you can see the executed example code with the output.

Convert a String to a Float in Python handle different number format

Here, we have a string "1,234,567.89" representing a number in the US format. Before converting it to a float, we use the replace() method to remove the comma separators. This preprocessed string is then passed to the float() function for conversion.

Check out How to Find All Occurrences of a Substring in a String Using Python?

Conclusion

In this tutorial, I have helped you to learn how to convert a string to a float in Python. I covered using float() method, and also covered how to handle invalid inputs, and different number formats with examples.

You may read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.