Convert a string to a float in Python

The simplest code, you can use to parse a string to float in Python.

float_value = float("123.456")

If you want to convert “123.456” to int, you can’t use int(“123.456”). First, you have to convert this value to float and then to int.

float_value = float("123.456")
int_value = int(float_value)

If you want to use one line, you can do this.

int_value = int(float("123.456"))

It can be done also to negative values. So the following code is valid.

int_value = int(float("-123.456"))

Parse a string to float if possible

Sometimes, when you try to convert float to string there might be a value that is not possible to convert, such as text or an empty string. In this situation, you can handle these exceptions in this way.

string_value1 = ''
string_value2 = '123.456'
string_value3 = 'just text'


def convert_to_float(string_value):
    try:
        return float(string_value)
    except:
        return False


print(convert_to_float(string_value1))
print(convert_to_float(string_value2))
print(convert_to_float(string_value3))

In this simple example, Python returns float. If it can return float, it returns False.

False
123.456
False

Parse a string to float and set precision

You can set precision of a converted string.

string_value = '123.556'


def convert_to_float(string_value, precision):
    try:
        float_value = float(string_value)
        return round(float_value, precision)
    except:
        return False


print(convert_to_float(string_value, 0))
print(convert_to_float(string_value, 1))
print(convert_to_float(string_value, 2))
print(convert_to_float(string_value, 3))
print(convert_to_float(string_value, 6))

output

124.0
123.6
123.56
123.556
123.556

This function will set the precision, and round the number.

Parse a string to float thousand separator

If you have data written with a thousand separator, you can use the following code to convert it automatically to int or float.

string_int = '1,000,000'
string_float = '1,000,000.58'

print(int(string_int.replace(',', '')))
print(float(string_int.replace(',', '')))
print(float(string_float.replace(',', '')))

This gives us the following output.

1000000
1000000.0
1000000.58

Parse a string to float with a scientific notation

If you use scientific notation, the float function will automatically convert such string to float.

a = '3.67E+00'
b = '1.35E+01'
c = '1.16E+02'
d = '1.16E-02'

print(float(a))
print(float(b))
print(float(c))
print(float(d))