English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
The float() method returns a floating-point number from a number or string.
The syntax of float() is:
float([x])
float() method takes one parameter:
x (optional) -The number or string that needs to be converted to a floating-point number.
If it is a string, then the string should contain a decimal point
Parameter type | Usage |
---|---|
Float number | Used as a floating-point number |
Integer | Used as an integer |
String |
Must contain decimal numbers. Leading and trailing spaces are removed. Optional use of “ +”,“-” symbol. Can include NaN, Infinity, inf (either uppercase or lowercase). |
float() method returns:
Equivalent floating-point number when passing parameters
If no parameter is passed, it is 0.0
If the parameter is out of the range of Python float, an OverflowError exception will occur
# Parameter is an integer print(float(10)) # Parameter is a floating point print(float(11.22)) # Parameter is a string float print(float("-13.33")) # Parameter is a string with spaces print(float(" -24.45\n")) # Parameter is a string, will throw a floating-point error print(float("abc"))
When running the program, the output is:
10.0 11.22 -13.33 -24.45 ValueError: could not convert string to float: 'abc'
# Parameter is NaN print(float("nan")) print(float("NaN")) # Parameter is inf/infinity print(float("inf")) print(float("InF")) print(float("InFiNiTy")) print(float("infinity"))
When running the program, the output is:
nan nan inf inf inf inf