Python float()

The float() returns an object of the float class that represents a floating-point number converted from a number or string.

Syntax:

float(x)

Parameters:

x: The element that should be converted.

Return Value:

Returns a float value.

The following example converts numbers and strings to float.

Example: float()
print("int to float: ", float(10))
print("int to float: ", float(-10))
print("string to float: ", float('10.2'))
print("string to float: ", float('-10.2'))
Output
int to float: 10.0
int to float: -10.0
string to float: 10.2
string to float: -10.2

It also converts scientific floating numbers to float.

Example: float()
print(float(3e-002))
print(float("3e-002"))
print(float('+1E3'))
Output
0.03 
0.03 
1000.0

The following converts boolean, nan, inf, Infinity to float.

Example: float()
print("True to float: ", float(True))
print("False to float: ", float(False))
print("Nan to float: ",float('nan'))
print("Infinity to float: ",float('inf'))
Output
True to float: 1.0
False to float: 0.0
Nan to float: nan
Infinity to float: inf

The float() method ignores the whitespace or carriage return.

Example: float()
print("int to float: ", float(       10))
print("string to float: ", float('      10 \n'))
Output
int to float: 10.0 
string to float: 10.0

The float() method throws the ValueError if x is not a valid number or numeric string.

Example: float()
print(float('x'))
Output
Traceback (most recent call last):
    print(float('x'))
ValueError: could not convert string to float: 'x'