Parse 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 be done also 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.

Parse a string to float and set precision

You can set precision of a converted string.


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.

This gives us the following output.

Parse a string to float with a scientific notation

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