Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท Built-in Functions

Python float() function

Reference for Python float(): convert numbers and strings to floating-point values, special values like inf and nan, precision limits and errors.

float() creates a floating-point number (a 64-bit IEEE 754 double on all mainstream platforms). It converts integers, numeric strings and any object that defines __float__() or __index__(). Called with no argument it returns 0.0.

Floats trade exactness for range: they can hold very large and very small magnitudes, but most decimal fractions such as 0.1 cannot be stored exactly. For money or exact decimal arithmetic, use decimal.Decimal.

Python
print(float("3.25"))
# 3.25

Try it

Python Converting values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python Special values and precision

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Syntax

Python
float()
float(x)
Name Description
x A number, a string or bytes-like text such as "3.14", or an object with __float__(). Strings may have surrounding whitespace, a sign, an exponent, underscores between digits, and the words inf, infinity and nan in any case.

Return value: a float. With no argument, 0.0.

Raises: ValueError for strings that are not valid numbers; TypeError for types that cannot be converted (such as None or a list); OverflowError for integers too large for a float.

Usage notes

  • Rounding errors are normal. 0.1 + 0.2 is 0.30000000000000004. Compare floats with math.isclose() or a tolerance, not ==.
  • nan is never equal to anything, including itself. Test with math.isnan().
  • Parsing is strict. float("1,5") fails; there is no locale support. Replace the comma yourself or use the locale module.
  • Integers beyond 2**53 lose exactness when converted, because a double has 53 bits of precision.
  • Truncation vs conversion. float(3) adds .0. To go the other way use int(), round(), math.floor() or math.ceil().
  • Printing. repr(float) gives the shortest string that round-trips to the same value; use format specs like f"{x:.2f}" for display.
  • Other number types. Decimal and Fraction convert with float(), possibly losing precision. complex does not convert.
  • Subclassing. float can be subclassed, and isinstance(True, float) is False although True converts to 1.0.