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.
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'))
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.
print(float(3e-002))
print(float("3e-002"))
print(float('+1E3'))
0.03
0.03
1000.0
The following converts boolean, nan, inf, Infinity to 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'))
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.
print("int to float: ", float( 10))
print("string to float: ", float(' 10 \n'))
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.
print(float('x'))
Traceback (most recent call last):
print(float('x'))
ValueError: could not convert string to float: 'x'