Convert a String to a Float in Python

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

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.

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

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

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.

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 the precision of a converted string.

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 a 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.

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 automatically converts such string to float.