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

ParameterDescription
x optional A number or a string such as "3.14", "1e-3" or "inf". Default: 0.0

Return value

A float.

Examples

Convert strings and numbersTry it yourself
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
Floating-point roundingTry it yourself
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
Handle bad inputTry it yourself
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.2 is 0.30000000000000004. Compare with a tolerance (math.isclose()), and use decimal.Decimal for money.
  • float("1,5") fails: commas aren't decimal separators. Replace them first or use locale.

Version history

VersionChange
Python 3.0Added
Python 3.6Underscores are allowed in numeric strings, e.g. "1_000.5".
Python 3.14Added the float.from_number() class method.