Con­vert­ing a Python string into a float can help you avoid errors that result from including non-numeric strings in arith­metic op­er­a­tions.

What kind of Python strings can be converted to floats?

If you want to convert a Python string to a float, the string needs to have a valid numerical rep­re­sen­ta­tion as a floating-point value. This means that it can contain numbers in decimal format, which includes decimal points and sci­en­tif­ic notation (such as "3.14" or "2.7e-3"). However, it can’t contain ad­di­tion­al char­ac­ters, spaces or char­ac­ters that don’t represent numerical values. If it does, the con­ver­sion won’t work.

String–float con­ver­sion is a basic function and is included in every version of Python. However, there might be subtle dif­fer­ences in how some methods and functions work in different versions. Be sure to keep an eye out for errors that can arise during con­ver­sions. For example, entering a string that doesn’t represent a valid number will give rise to an error. And special values like NaN (Not a Number) and Infinity can’t be converted into floats. That means de­vel­op­ers working with con­ver­sions need to be able to handle errors ap­pro­pri­ate­ly. Using try/except blocks to catch and react to errors is one way to do this.

How to convert Python strings with float()

The float() function is a built-in Python method that converts strings to floats. It’s often used to change user input from strings to numeric formats so that the input can be used in cal­cu­la­tions or numerical op­er­a­tions. In programs that work with various kinds of data, float() is used to ensure that data remains con­sis­tent by con­vert­ing values into a numerical format.

To convert Python strings to floats, use float() and enter a valid string as the argument:

str1 = "3.1416"
float_value = float(str1)
print(float_value) # Output: 3.1416
python

You can also convert other numerical types like int and complex into a floating number by running them through float().

Try/except blocks can be used to catch invalid user input when con­vert­ing strings to floats:

while True:
    user_input = input("Enter a number: ")
    try:
        float_value = float(user_input)
        print("Entered number as float:", float_value)
        break # Exit the loop if the conversion was successful
    except ValueError:
        print("Invalid input! Please enter a numeric value.")
        # The loop continues to prompt for valid input
python

The above code is a loop that prompts users to enter a number. It then attempts to convert that value into a floating number. In the try block, float(user_input) is meant to convert the string entered by the user into a float. If the con­ver­sion was suc­cess­ful, the number is stored under float_value and returned. The break statement then ter­mi­nates the loop and moves on with the program.

If a Val­ueEr­ror occurs when con­vert­ing the string to a float, the code in the except block is executed. This can happen if the user enters a value that can’t be converted into a float, like a letter. In this case, a message says that the input is invalid and the loop requests valid input again.

How to convert Python strings to floats with NumPy

If you want to convert a Python string to a float with NumPy, you can use the function numpy.float64(). It will give you a 64-bit floating number.

import numpy as np
string_value = "3.1416"
float_value = np.float64(string_value)
print(float_value) # Output: 3.1416
python

First you’ll need to import NumPy in your script if it’s not already installed. You can then use NumPy to apply the function numpy.float64() to the string string_value to convert it into a 64-bit floating number.

How to use str()

If, on the other hand, you want to convert a float into a string, you can use the str() function. This function converts other values into strings.

float_number = 3.1416
string_number = str(float_number)
print(string_number) # Output: "3.1416"
python

In the above example, the float value 3.1416 is converted into the string "3.1416" using str().

str() is also useful for con­cate­nat­ing several float values with f-strings (a Python string format).

float_value1 = 3.1416
float_value2 = 2.7182
float_value3 = 1.6180
string_concatenation = f"Concatenation of: {str(float_value1)}, {str(float_value2)}, and {str(float_value3)}"
print(string_concatenation) # Concatenation of: 3.1416, 2.7182, and 1.6180
python

Note that when con­vert­ing floats to strings with str(), the resulting string will then be rep­re­sent­ed as text and will no longer be available for numerical cal­cu­la­tions or math­e­mat­i­cal op­er­a­tions. To use it in cal­cu­la­tions, you’ll have to turn it back into a numerical form (like a float).

Tip

Read about other kinds of con­ver­sions in our Digital Guide. We explain how to convert Python strings to lists and Python strings to datetime objects.

Web hosting
Get your site online fast without breaking the bank
  • Fast page loads while cutting costs by 60%
  • Keep your site open 24/7 with 99.99% uptime
  • Never run out of space with unlimited storage

Reviewer

Go to Main Menu