Open Python and type this:
print(0.1 + 0.2)You'd expect 0.3. Python gives you this:
0.30000000000000004And it gets stranger:
print(0.1 + 0.2 == 0.3)FalseIf you're learning to code, this is the moment you start wondering whether you broke something. You didn't. Python is doing exactly what it was designed to do, and so are JavaScript, Java, C# and almost every other language. Try 0.1 + 0.2 in your browser's console and you'll get the same 0.30000000000000004.
Let's look at why, and what to do about it.
Computers store numbers in binary
You count in base 10: every digit is a number of ones, tens, hundreds, and after the decimal point, tenths, hundredths and so on.
Computers count in base 2 (binary). After the "binary point" they only have halves, quarters, eighths, sixteenths…
Some numbers fit perfectly into that system:
0.5is one half: exact.0.25is one quarter: exact.0.75is a half plus a quarter: exact.
But 0.1, one tenth, can't be built from halves, quarters and eighths. In binary it's an endless repeating pattern:
0.0001100110011001100110011...The same problem you already know: 1/3
You've seen this in base 10. Try writing one third as a decimal:
0.3333333333...The threes never stop. At some point you have to cut it off, and the number you wrote down is almost one third, but not exactly.
The computer has the same problem with 0.1, just in binary. It has a fixed amount of space for each number (64 bits), so it stores the closest value it can fit. You can see the number Python actually stored:
from decimal import Decimal
print(Decimal(0.1))0.1000000000000000055511151231257827021181583404541015625So 0.1 is really a tiny bit more than 0.1. The same goes for 0.2. Add two slightly-off numbers and the tiny errors add up. That's where the extra ...04 comes from.
It's not only 0.1 + 0.2:
print(0.1 + 0.7)0.7999999999999999Why print(0.1) still shows 0.1
If 0.1 is stored as 0.1000000000000000055..., why does print(0.1) show 0.1?
Python is being helpful. When it prints a float, it shows the shortest number that maps back to the same stored value. For 0.1, that's simply 0.1. But after the addition, the result lands on a slightly different stored value, and the shortest way to write that one is 0.30000000000000004.
How to fix it
1. Round when you display a result
If you only need to show the number, round it:
total = 0.1 + 0.2
print(round(total, 2))
print(f"{total:.2f}")0.3
0.302. Never compare floats with ==
This is the real lesson. Instead of asking "are these exactly equal?", ask "are these close enough?":
import math
print(math.isclose(0.1 + 0.2, 0.3))Truemath.isclose() lets a tiny difference through, which is exactly what you want when working with decimals.
3. Use Decimal when every cent matters
For money and other places where you need exact decimal math, use the decimal module. Pass the numbers in as strings:
from decimal import Decimal
print(Decimal("0.1") + Decimal("0.2"))0.3Strings matter here. Decimal(0.1) would copy the already-imprecise float, and you'd be back to 0.1000000000000000055....
One more surprise: round() isn't magic either
Now that you know the trick, this one makes sense:
print(round(2.675, 2))2.67You'd expect 2.68. But 2.675 is stored as slightly less than 2.675, so it rounds down. You can check with the same trick as before:
from decimal import Decimal
print(Decimal(2.675))2.67499999999999982236431605997495353221893310546875Same cause, different symptom.
Quick summary
- Showing a decimal to a user:
round(x, 2)orf"{x:.2f}". - Checking if two decimals are equal:
math.isclose(a, b), never==. - Money or exact decimal math:
Decimal("0.1"), with strings.
Try it yourself
Reading this is one thing. The rule really sticks after you hit the bug yourself. Open Python and try:
print(0.1 + 0.2 == 0.3). Predict the answer first.- Find another pair of decimals that doesn't add up cleanly.
- Fix the comparison with
math.isclose().
Decimals aren't the only place where Python's types surprise beginners: mixing text and numbers is even more common, see Python TypeError: unsupported operand type(s) for -: 'int' and 'str'. And if you're still deciding which language to start with, see Which programming language should you learn first?
