Python float type
last modified November 29, 2026 Python 3.15
In this article we show how to work with the float type in
Python.
A float is a number with a fractional part, such as 2.5 or
0.001. Python floats are IEEE 754 double-precision numbers: they are stored
in 64 bits as a binary fraction and an exponent. This gives about 15 to 17
significant decimal digits and a range up to about 1.8 × 10308.
Because the fraction is binary, most decimal values such as 0.1 can only be
stored approximately, and that is the source of most float surprises.
Float literals
A float literal contains a decimal point, an exponent, or both. The true
division operator / always returns a float, and an expression
that mixes an int with a float gives a float.
price = 12.5 distance = 3.8e5 half = 7 / 2 print(price, distance, half) print(type(price)) print(type(7 // 2), type(7 / 2)) print(2 * 0.5, 4 + 1.0)
The literal 3.8e5 means 3.8 × 105. Division
with / gives 3.5, while floor division // of two
integers stays an integer. In 2 * 0.5 and 4 + 1.0,
the integer operand is converted to a float before the operation, so the
results are floats even though they have no fractional part.
$ python first_floats.py 12.5 380000.0 3.5 <class 'float'> <class 'int'> <class 'float'> 1.0 5.0
Converting to float
The float function converts strings and integers to floats.
Going the other way, int drops the fractional part, while
round rounds to the nearest integer.
print(float('2.5'))
print(float(' -12 '))
print(float('1_000.25'))
print(float('6.02e23'))
print(float(3))
print(int(3.99))
print(int(-3.99))
print(round(3.99))
The string may contain surrounding whitespace, a sign, underscores between
digits, and an exponent. int truncates towards zero, so 3.99
becomes 3 and -3.99 becomes -3. A string that is not a number, such as
'abc', raises a ValueError.
$ python conversions.py 2.5 -12.0 1000.25 6.02e+23 3.0 3 -3 4
Limited precision
Most decimal fractions have no finite binary representation, just as 1/3 has no finite decimal representation. The float stored for 0.1 is the nearest binary fraction, not exactly 0.1, and the small errors show up in arithmetic.
a = 0.1 + 0.2
b = 0.3
print(a)
print(b)
print(a == b)
print(f'{a:.20f}')
print(f'{b:.20f}')
The sum of 0.1 and 0.2 is printed as 0.30000000000000004, and it is not equal to 0.3. Python prints the shortest decimal string that maps back to the same float, which hides the error for single literals. Asking for 20 decimal places shows that neither value is exactly what was typed: the sum is slightly above 0.3 and the literal 0.3 slightly below it.
$ python precision.py 0.30000000000000004 0.3 False 0.30000000000000004441 0.29999999999999998890
The exact stored value
Every float is exactly a fraction whose denominator is a power of two. The
as_integer_ratio method returns this fraction, and converting
a float to Decimal prints all its decimal digits.
from decimal import Decimal print((0.5).as_integer_ratio()) print((0.1).as_integer_ratio()) print((0.1).hex()) print(Decimal(0.1)) print(Decimal(0.5))
The value 0.5 is 1/2, a power of two, so it is stored exactly. The value 0.1
is stored as 3602879701896397 / 255. The hex method
shows the repeating binary pattern 999...a, rounded up in the
last digit. Decimal(0.1) reveals the exact value, which is a
little more than 0.1. Integers up to 253 and fractions such as
0.5, 0.25, or 0.375 are exact.
$ python exact_value.py (1, 2) (3602879701896397, 36028797018963968) 0x1.999999999999ap-4 0.1000000000000000055511151231257827021181583404541015625 0.5
Comparing floats
Since computed floats carry small errors, testing them with ==
is fragile. The math.isclose function checks whether two values
are within a tolerance of each other.
import math a = 0.1 + 0.2 print(a == 0.3) print(abs(a - 0.3) < 1e-9) print(math.isclose(a, 0.3)) print(math.isclose(1e-12, 0.0)) print(math.isclose(1e-12, 0.0, abs_tol=1e-9)) print(math.isclose(1_000_000.0, 1_000_001.0, rel_tol=1e-5))
By default, isclose uses a relative tolerance of 1e-9: the
values must agree in about nine significant digits. A relative tolerance
does not work near zero, because nothing is relatively close to 0.0 except
0.0 itself; for such comparisons we add an absolute tolerance with
abs_tol. The last line allows a relative difference of 1e-5,
so one million and one million and one count as equal.
$ python compare.py False True True False True True
Summing floats
Each addition rounds its result, and the rounding errors accumulate in long
calculations. Since Python 3.12, the built-in sum uses
compensated summation for floats, and math.fsum returns the
correctly rounded sum.
import math
total = 0.0
for i in range(10):
total += 0.1
print(total)
print(sum([0.1] * 10))
print(math.fsum([0.1] * 10))
values = [1e16, 1.0, -1e16]
print(values[0] + values[1] + values[2])
print(math.fsum(values))
Adding 0.1 ten times in a loop gives 0.9999999999999999. Both
sum and math.fsum keep track of the lost low-order
bits and return 1.0. The second example adds 1.0 to 1e16, where the spacing
between floats is 2.0, so the 1.0 is lost and the plain additions give 0.0;
fsum returns the correct 1.0. The order of operations matters
for floats: addition is not associative.
$ python summation.py 0.9999999999999999 1.0 1.0 0.0 1.0
Range of floats
The sys.float_info named tuple describes the float format of the
platform. On all common platforms it is IEEE 754 double precision.
import sys print(sys.float_info.max) print(sys.float_info.min) print(sys.float_info.epsilon) print(sys.float_info.dig) print(sys.float_info.max * 2) print(5e-324) print(5e-324 / 2) print(1.0 + sys.float_info.epsilon / 2 == 1.0)
max is the largest finite float, and min the
smallest positive normalized one. Smaller subnormal values exist down to
5e-324; half of that underflows to 0.0. epsilon is the gap
between 1.0 and the next float, and dig is the number of
decimal digits that always survive a round trip through a float. Overflow
in multiplication gives inf without an error. Adding half of
epsilon to 1.0 has no effect at all.
$ python limits.py 1.7976931348623157e+308 2.2250738585072014e-308 2.220446049250313e-16 15 inf 5e-324 0.0 True
Spacing of floats
Floats are not evenly spaced. The gap between neighbouring values grows with
their magnitude. The math.ulp function returns this gap, the
unit in the last place, and math.nextafter returns the
neighbouring float.
import math
for x in [1.0, 1000.0, 1e9, 1e16]:
print(x, math.ulp(x))
print(math.nextafter(1.0, 2.0))
print(2.0 ** 53)
print(2.0 ** 53 + 1)
print(float(2 ** 53 + 1) == 2 ** 53)
print(1e16 + 1 == 1e16)
Near 1.0, floats are about 2.2e-16 apart; near 1e16, they are 2.0 apart.
From 253 on, a float cannot hold every integer: 253 + 1
is rounded back to 253, and adding 1 to 1e16 changes nothing.
Python integers have unlimited precision, so large whole numbers such as IDs
or money in cents should be kept as int, not float.
$ python spacing.py 1.0 2.220446049250313e-16 1000.0 1.1368683772161603e-13 1000000000.0 1.1920928955078125e-07 1e+16 2.0 1.0000000000000002 9007199254740992.0 9007199254740992.0 True True
Infinity and NaN
IEEE 754 defines special values: positive and negative infinity and NaN, not
a number. They are created with float('inf') and
float('nan') or taken from math.inf and
math.nan.
import math
big = float('inf')
missing = float('nan')
print(big, -big, big + 1, big - big)
print(missing == missing)
print(math.isnan(missing), math.isinf(big))
print(math.inf == big)
print(max(1.0, missing), max(missing, 1.0))
print(-0.0, 0.0 == -0.0, math.copysign(1.0, -0.0))
Infinity absorbs finite additions, and inf - inf is undefined,
so it gives NaN. A NaN is not equal to anything, not even to itself; use
math.isnan to detect it. Comparisons with NaN are always false,
which is why max returns different results depending on the
argument order. Floats also have a negative zero, which equals 0.0 but
keeps its sign, as copysign shows.
$ python special.py inf -inf inf nan False True True True 1.0 nan -0.0 True -1.0
Rounding and division
The round function rounds halves to the nearest even number,
which avoids a bias in large sums. The math module provides
floor, ceil, and trunc.
import math
print(round(2.5), round(3.5), round(-2.5))
print(round(2.675, 2))
print(f'{2.675:.2f}')
print(f'{2.675:.20f}')
print(math.floor(-2.5), math.ceil(-2.5), math.trunc(-2.5))
print(7.5 // 2, -7.5 // 2)
print(7.5 % 2, -7.5 % 2)
Both 2.5 and -2.5 round to the even neighbour 2 or -2, while 3.5 rounds to 4.
round(2.675, 2) gives 2.67, not 2.68, because the stored value
is 2.67499999...; formatting with .2f rounds the same stored
value. floor rounds down, ceil up, and
trunc towards zero. Floor division and modulo also work with
floats, and they follow the floor rule: -7.5 // 2 is -4.0, and
the remainder has the sign of the divisor. More details are in
Python round.
$ python rounding.py 2 4 -2 2.67 2.67 2.67499999999999982236 -3 -2 -2 3.0 -4.0 1.5 0.5
Float methods
The float type has a few methods of its own. Python 3.14 added the
float.from_number class method, which accepts only numbers,
not strings.
x = 2.75
print(x.is_integer(), (3.0).is_integer())
print(x.as_integer_ratio())
print(x.hex(), float.fromhex('0x1.6p+1'))
print(float.from_number(5))
print(x.real, x.imag, x.conjugate())
is_integer tells whether the value has no fractional part. The
value 2.75 is 11/4, which is why it is stored exactly. hex and
float.fromhex convert to and from an exact hexadecimal form,
useful for storing floats as text without any loss. The real,
imag, and conjugate members exist so that floats
can be used where complex numbers are expected.
$ python methods.py False True (11, 4) 0x1.6000000000000p+1 2.75 5.0 2.75 0.0 2.75
Formatting floats
To display a float, we format it to a given number of digits. The format specification is written after a colon in an f-string.
x = 1234.5678
small = 0.000012345
print(f'{x:.2f}')
print(f'{x:,.2f}')
print(f'{x:10.1f}|')
print(f'{x:e}')
print(f'{small:g}')
print(f'{0.257:.1%}')
print(repr(1 / 3), str(1 / 3))
The .2f format gives two decimal places, a comma adds
thousands separators, and the number before the dot sets the field width.
The e format uses scientific notation, and g
chooses between fixed and scientific notation. The % format
multiplies by 100. repr and str both give the
shortest string that reads back as the same float. The full format syntax
is covered in Python f-strings.
$ python formatting.py
1234.57
1,234.57
1234.6|
1.234568e+03
1.2345e-05
25.7%
0.3333333333333333 0.3333333333333333
Exact alternatives
When decimal values must be exact, as with money, floats are the wrong type.
The standard library has two exact number types: Decimal for
decimal fractions and Fraction for rational numbers.
from decimal import Decimal
from fractions import Fraction
prices = [0.10, 0.20, 0.30]
print(sum(prices))
prices = [Decimal('0.10'), Decimal('0.20'), Decimal('0.30')]
print(sum(prices))
third = Fraction(1, 3)
print(third + third + third)
print(Fraction(0.1))
The float sum of the three prices prints as 0.6 only because the errors
happen to cancel out; such luck cannot be relied upon. The
Decimal values are created from strings and add up exactly,
keeping two decimal places. Three thirds as Fraction values
give exactly 1. Creating a Fraction from the float 0.1 shows,
again, that the float is not one tenth. Both types are slower than floats.
They are covered in Python Decimal.
$ python money.py 0.6 0.60 1 3602879701896397/36028797018963968
Source
Numeric types – int, float, complex, Floating-point arithmetic: issues and limitations, math – Mathematical functions, sys.float_info
In this article we have created and converted floats, shown why 0.1 + 0.2 is not 0.3, compared and summed floats safely, looked at the range and spacing of floats, infinity, NaN, and negative zero, and rounded, formatted, and replaced floats with exact types. See also Python data types, Python Decimal, and Python pitfalls.
Author
List all Python tutorials.