The most famous surprise in programming
Ask Python for 0.1 + 0.2 and it answers 0.30000000000000004. This is not a bug. Computers store floats in binary (base 2), and 0.1 has no exact binary representation, the same way 1/3 has no exact decimal form (0.3333... forever). Python stores the closest binary value it can, and the leftover error occasionally becomes visible.
This matters the first time money or measurements enter your code: a price total that prints with 17 decimal places, or an == comparison that fails for no visible reason. Two working rules:
- Never compare floats with
==. Round both sides first, or check that the difference is tiny. - Format for display. An f-string with
:.2fshows the number the way a human expects, without changing the stored value.
Code exercise · python
Run it and see the error with your own eyes, then watch round() rescue the comparison.
Quiz
Why does `0.1 + 0.2 == 0.3` evaluate to False?
Working with money anyway
Serious systems dodge the problem by doing money math in whole cents, because ints are exact, and only converting to dollars for display. Two more number tools worth knowing now:
abs(x)gives the distance from zero:abs(-7)is7. It powers the standard "how far apart are these numbers" check,abs(a - b).round(x, 2)rounds to 2 decimal places, but it rounds the stored binary value, soround(2.675, 2)gives2.67, not the2.68you might expect. One more reason whole cents is the professional habit.
Code exercise · python
Your turn, the cents trick. Add the two prices, convert the sum to whole cents by multiplying by 100 and rounding with round(), print the cents, then print `total: 0.30` by dividing back and formatting with `:.2f`.