Python Numbers and Math · Lesson 15 of 149

Python Float Precision

What you will learn

  • Why 0.1 + 0.2 does not equal 0.3
  • How a float is stored, and what is exactly stored for 0.1
  • Three traps: comparing with ==, cutting with int(), and money
  • The safe habits: round for display, math.isclose to compare
  • When to leave floats behind

1. The surprise

print(0.1 + 0.2)
print(0.1 + 0.2 == 0.3)
0.30000000000000004
False

This is not a Python bug, and it is not a mistake in your code. It happens in nearly every programming language, because of how computers store decimal numbers.

Quick check: is `0.5 + 0.25 == 0.75` also false?

No, it is True. 0.5 and 0.25 are exact in binary (halves and quarters), so the sum is exact. The trouble comes from numbers like 0.1.

2. Why it happens

A computer stores a float as a binary fraction: a sum of halves, quarters, eighths and so on. Python uses the standard IEEE 754 "double precision" format, which keeps 53 binary digits of precision.

Some numbers fit perfectly in binary (0.5, 0.25, 0.75). Others, such as 0.1, would need a binary fraction that goes on forever, just as 1/3 goes on forever in decimal (0.3333...). So the computer stores the closest value it can.

You can see what is really stored for 0.1:

print(format(0.1, ".20f"))
print((0.1).as_integer_ratio())
0.10000000000000000555
(3602879701896397, 36028797018963968)
  • The stored value is 0.1000000000000000055..., slightly more than 0.1.
  • as_integer_ratio() gives it as a fraction: 3602879701896397 divided by 36028797018963968, which is 2 to the power of 55.

When you print 0.1, Python shows the shortest text that gives back the same float, so it looks like 0.1. The tiny error stays hidden until you calculate with it: 0.1 + 0.2 adds two slightly-wrong numbers, and the small errors show up in the answer.

3. Trap 1: comparing with ==

Because results carry tiny errors, two floats that should be equal may not be:

print(0.1 * 3 == 0.3, 1.1 + 2.2 == 3.3)
print(1.1 + 2.2)
False False
3.3000000000000003

Never compare floats with == when they come from calculations. Use math.isclose, which asks "are these close enough?":

import math
print(0.1 + 0.2 == 0.3)
print(math.isclose(0.1 + 0.2, 0.3))
False
True

isclose has two settings. The default relative tolerance is 1e-09 (about nine digits). Near zero, a relative test is useless, so add an absolute tolerance:

print(math.isclose(0, 1e-12))
print(math.isclose(0, 1e-12, abs_tol=1e-9))
False
True

You can also compare rounded values, as in round(0.1 + 0.2, 2) == 0.3 (which is True), when you know how many places matter.

4. Trap 2: cutting with int()

int() cuts the decimal part, so a result that is a tiny bit too small loses a whole unit:

print(0.1 + 0.7)
print((0.1 + 0.7) * 10)
print(int((0.1 + 0.7) * 10))
0.7999999999999999
7.999999999999999
7

You might expect 8. The same happens with 4.35 * 100, which is 434.99999999999994. If you want the nearest whole number, use round, not int:

print(int(4.35 * 100), round(4.35 * 100))
434 435

5. Trap 3: money

Money needs exact cents, which floats cannot always give. There are two safe choices:

Method How Example
Whole numbers keep the amounts in the smallest unit (cents) as an int 1999 * 3 is 5997 cents
decimal module exact decimal arithmetic (lesson 3.5) Decimal("19.99") * 3
price_cents = 1999
total_cents = price_cents * 3
print(total_cents, total_cents / 100)
5997 59.97

All the arithmetic is done in exact whole numbers. Only the final display divides by 100.

6. Showing numbers: round and format

To show a result, round it for the reader. The stored value does not change, only the text:

x = 0.1 + 0.2
print(round(x, 2))
print(f"{x:.2f}")
print(f"{1234567.891:,.2f}")
0.3
0.30
1,234,567.89
Format Meaning
:.2f exactly 2 digits after the point
:,.2f the same, with commas between thousands

Remember that round follows "ties to even" and the stored value (lesson 3.3): f"{2.675:.2f}" shows 2.67.

7. Adding many floats

Adding many floats adds many small errors. The standard library has math.fsum, which adds float values while keeping track of the lost digits, so it is more accurate than adding them one by one:

import math
print(math.fsum([0.1] * 10))
1.0

Worked example: a safe "is it paid?" check

A bill is 0.1 + 0.2 = 0.30. A customer pays 0.3. Is the bill paid?

Step What you do Result
1 The tempting test 0.1 + 0.2 == 0.3 False: wrong answer
2 Use math.isclose(0.1 + 0.2, 0.3) True
3 Better: keep cents as whole numbers, 10 + 20 == 30 True, exact
print(10 + 20 == 30)
True

With whole-number cents there is no error to worry about.

Common mistakes

  • Comparing floats with == after a calculation.
  • Using int() where you meant "round to nearest".
  • Storing money in floats. Use whole cents or decimal.
  • Believing print(0.1) proves 0.1 is exact. Python only shows the shortest matching text.
  • Using isclose near zero without abs_tol.

Key takeaways

  • Floats are stored as binary fractions (53 binary digits); most decimals such as 0.1 are only approximate.
  • So 0.1 + 0.2 is 0.30000000000000004, and 0.1 + 0.2 == 0.3 is False.
  • Compare with math.isclose (add abs_tol near zero); cut with round, not int.
  • Show results with round(x, 2) or f"{x:.2f}".
  • For money use whole cents or the decimal module.

Practice

1. Why is 0.1 + 0.2 == 0.3 false?

Show answer

0.1 and 0.2 cannot be stored exactly as binary fractions, so the sum is a tiny bit away from the stored 0.3.

2. Which test is better: a == b or math.isclose(a, b), for two floats from calculations?

Show answer

math.isclose(a, b), because it allows for the tiny errors.

3. What does int(4.35 * 100) give? Which function gives the nearest whole number instead?

Show answer

434, because 4.35 * 100 is 434.99999999999994 and int cuts. round(4.35 * 100) gives 435.

4. Write a safe way to add three prices, 4.99, 5.01 and 10.00, with no float error.

Show answer

Use cents: 499 + 501 + 1000, which gives 2000 cents, then show 2000 / 100 as 20.0. Or use the decimal module (lesson 3.5).

5. How do you show 3.14159 with exactly 2 decimals using an f-string?

Show answer

f"{3.14159:.2f}", which gives 3.14.

6. When does math.isclose(0, 1e-12) give False, and how do you change it?

Show answer

With the default settings, a number is only "close" to zero if it is almost exactly zero, so 1e-12 is not close. Add an absolute tolerance: math.isclose(0, 1e-12, abs_tol=1e-9) gives True.