Reference Materials
Created with over a decade of experience.
Certification Courses
Created with over a decade of experience and thousands of feedback.
Built-in Functions
- Python abs()
- Python any()
- Python all()
- Python ascii()
- Python bin()
- Python bool()
- Python bytearray()
- Python callable()
- Python bytes()
- Python chr()
- Python compile()
- Python classmethod()
- Python complex()
- Python delattr()
- Python dict()
- Python dir()
- Python divmod()
- Python enumerate()
- Python staticmethod()
- Python filter()
- Python eval()
- Python float()
- Python format()
- Python frozenset()
- Python getattr()
- Python globals()
- Python exec()
- Python hasattr()
- Python help()
- Python hex()
- Python hash()
- Python input()
- Python id()
- Python isinstance()
- Python int()
- Python issubclass()
- Python iter()
- Python list() Function
- Python locals()
- Python len()
- Python max()
- Python min()
- Python map()
- Python next()
- Python memoryview()
- Python object()
- Python oct()
- Python ord()
- Python open()
- Python pow()
- Python print()
- Python property()
- Python range()
- Python repr()
- Python reversed()
- Python round()
- Python set()
- Python setattr()
- Python slice()
- Python sorted()
- Python str()
- Python sum()
- Python tuple() Function
- Python type()
- Python vars()
- Python zip()
- Python __import__()
- Python super()
Python float()
The float() method returns a floating point number from a number or a string.
Example
int_number = 25
# convert int to float
float_number = float(int_number)
print(float_number)
# Output: 25.0
float() Syntax
The syntax for float() is:
float([x])
float() Parameters
The float() method takes a single parameter:
- x (Optional) - number or string that needs to be converted to floating point number
If it's a string, the string should contain decimal points
| Parameter Type | Usage |
|---|---|
| Float number | Use as a floating number |
| Integer | Use as an integer |
| String | Must contain decimal numbers. Leading and trailing whitespaces are removed. Optional use of "+", "-" signs. Could contain NaN, Infinity, inf (lowercase or uppercase). |
float() Return Value
The float() method returns:
- Equivalent floating point number if an argument is passed
- 0.0 if no arguments passed
OverflowErrorexception if the argument is outside the range of Python float
Example 1: How float() works in Python?
# for integers
print(float(10))
# for floats
print(float(11.22))
# for string floats
print(float("-13.33"))
# for string floats with whitespaces
print(float(" -24.45\n"))
# string float error
print(float("abc"))
Output
10.0 11.22 -13.33 -24.45 ValueError: could not convert string to float: 'abc'
Example 2: float() for infinity and Nan(Not a number)?
# for NaN
print(float("nan"))
print(float("NaN"))
# for inf/infinity
print(float("inf"))
print(float("InF"))
print(float("InFiNiTy"))
print(float("infinity"))
Output
nan nan inf inf inf inf
Also Read:
Did you find this article helpful?
