float() overview
The Python built-in function float can be used to turn values into float. It us mostly used to turn integers and strings into float values.
However it can also be used to truncate unnecessary zeros from float values.
Python convert int to float
To convert int to float in Python use the float() function as follows:
my_int = 5
print(float(my_int))
5.0
Python convert string to float
To convert string to float in Python use the float() function as follows:
my_str = '5.0'
my_str2 = ' 5.0 \n'
print(float(my_str))
print(float(my_str2))
5.0
5.0
The float function can be used for strings with whitespaces.
Python truncate float to 1 decimal place
In case the float function is used with float values it is simply returned. The print function will truncate unnecessary zeros.
my_float = 5.0000
print(float(my_float))
5.0
float() for NaN (not a number)
print(float('nan'))
print(float('NaN'))
nan
nan
float() for inf/infinity
print(float('INF'))
print(float('INFINITY'))
inf
inf
float() Syntax
The float() function accepts one argument of the type integer, string or float.
float([float])
float([int])
float([string])
float() returns
The float() method returns:
The equivalent floating point number if a valid argument is passed.
If no argument is passed:
0.0 is returned.
If the argument is outside the range of Python float:
OverflowError exception is returned.
To find the range of Python float for your system use sys.float_info().