Python float()
Python float() class
The float() class in Python returns a floating point number constructed from a number or string x.
Syntax
class float([x])
Parameter
x: This parameter represents a number or a string that can be converted into a floating point number
Return
This function returns a floating point number.
Example 1
#Python program explaining
# the float() class
val=6
print("value: ",val)
#Applying float() funcion
x = float(val)
print("After float() function: ",x)
Output
value: 6 After float() function: 6.0
Example 2
#Python program explaining
# the float() class
print(float(121.89))
# for floating point numbers
print(float(18))
# for integer type strings
print(float("23"))
# for floating type strings
print(float("-160.4"))
# for string floats with whitespaces
print(float(" -214.98 \n"))
Output
121.89 18.0 23.0 -160.4 -214.98
Example 3
#Python program explaining
# the float() class
# Error is generated for string values
print(float("float"))
Output
Traceback (most recent call last):
File "main.py", line 5, in <module>
print(float("float"))
ValueError: could not convert string to float: 'float' 