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.
print(float("3.25")) # 3.25
Try it
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.
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
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.2is0.30000000000000004. Compare floats withmath.isclose()or a tolerance, not==. nanis never equal to anything, including itself. Test withmath.isnan().- Parsing is strict.
float("1,5")fails; there is no locale support. Replace the comma yourself or use thelocalemodule. - Integers beyond
2**53lose exactness when converted, because a double has 53 bits of precision. - Truncation vs conversion.
float(3)adds.0. To go the other way useint(),round(),math.floor()ormath.ceil(). - Printing.
repr(float)gives the shortest string that round-trips to the same value; use format specs likef"{x:.2f}"for display. - Other number types.
DecimalandFractionconvert withfloat(), possibly losing precision.complexdoes not convert. - Subclassing.
floatcan be subclassed, andisinstance(True, float)isFalsealthoughTrueconverts to1.0.
Related
int(),round(),complex(),str()- float methods, numeric types
- Lessons: Numbers, Type conversion