Python 3 reference · Built-in Functions
Python float() Function
Convert a number or numeric string to a floating-point number. Also understands 'inf', '-inf' and 'nan'.
Python 3 Since 3.0
Syntax
float(x=0.0)
Parameters
| Parameter | Description |
|---|---|
x optional |
A number or a string such as "3.14", "1e-3" or "inf". Default: 0.0 |
Return value
A float.
Examples
print(float("3.14"), float(" 42 "), float(7))
print(float("1_000.5"))
print(float("inf") > 10 ** 100)
Output
3.14 42.0 7.0 1000.5 True
print(0.1 + 0.2)
print(round(0.1 + 0.2, 2))
print(abs((0.1 + 0.2) - 0.3) < 1e-9)
Output
0.30000000000000004 0.3 True
for text in ["12.5", "abc"]:
try:
print(float(text))
except ValueError:
print(f"not a number: {text!r}")
Output
12.5 not a number: 'abc'
Common mistakes
- Floats are binary approximations:
0.1 + 0.2is0.30000000000000004. Compare with a tolerance (math.isclose()), and usedecimal.Decimalfor money. float("1,5")fails: commas aren't decimal separators. Replace them first or uselocale.
Version history
| Version | Change |
|---|---|
| Python 3.0 | Added |
| Python 3.6 | Underscores are allowed in numeric strings, e.g. "1_000.5". |
| Python 3.14 | Added the float.from_number() class method. |
Related
int()· Convert a number or string to an integer. Floats are truncated toward zero, and strings can be in any base from 2 to 36.round()· Round a number to a given number of decimal places. Halfway values round to the nearest even number (banker's rounding).complex()· Create a complex number from a real and an imaginary part, or parse one from a string such as '1+2j'.str()· Convert a value to its readable text form, or decode bytes into a string. Strings are immutable sequences of characters.- Python Numbers · tutorial
- Python Casting · tutorial