Lessons · Python · comparing decimals
Decimals that are almost equal
0.1 + 0.2 is 0.30000000000000004, so compare floats with a tolerance, never with ==.
Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.
What it is for
Money totals, measurements, percentages: any sum of decimals drifts by a hair. A test of == that fails on a Tuesday because of rounding is a classic bug.
How to think about it
Ask: are these values the result of arithmetic? If so, compare abs(a - b) < small_number, or use math.isclose. For money, work in integer cents instead.
Worked example
a = 0.1 + 0.20.30000000000000004 in binary floating point.
print(a == 0.3)False. The bug.
print(abs(a - 0.3) < 1e-9)True. Close enough, and stated as such.
import math; print(math.isclose(a, 0.3))The standard tool for exactly this.
Your turn
Check two totals agree to within a cent.
same = abs(total_a - total_b) <
Solve one with the tests running
The trap
Fixing it by rounding both sides. round(2.675, 2) gives 2.67, not 2.68, for the same reason. Tolerance, not rounding.
Practise comparing decimals on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.