The float() method returns a floating point number from a number or a string.
Syntax
float(x)float() Parameters
Python float() function parameters:
| Parameter | Condition | Description |
|---|---|---|
x |
Optional | A number or a string that can be converted into a floating point number |
float() Return Value
Python float() function returns:
- Equivalent floating point number if an argument is passed
0.0if no arguments passedOverflowErrorexception if the argument is outside the range of Python float
Examples
Example 1: basic example of float() function
int_number = 123
float_number = float(int_number)
print(float_number) # Output: 123.0output
123.0Example 2: common cases of float() function
print(float(10))
print(float(12.34))
print(float("-12.34"))
print(float(" -12.34\n"))
print(float("abc"))output
10.0
12.34
-12.34
-12.34
Traceback (most recent call last):
File "main.py", line 14, in <module>
print(float("abc"))
ValueError: could not convert string to float: 'abc'Example 3: float() function for infinity and NaN (Not a Number)
print(float("nan"))
print(float("NaN"))
print(float("inf"))
print(float("InF"))
print(float("InFiNiTy"))
print(float("infinity"))output
nan
nan
inf
inf
inf
inf