Run 0.1 + 0.2 in almost any programming language and you will get 0.30000000000000004. This is not a bug in the language. It is how computers represent most fractions.
Why it happens
Computers store numbers in binary. Just as 1/3 has no finite decimal form (0.333...), 1/10 has no finite binary form. The common IEEE 754 double-precision format keeps about 15 to 17 significant decimal digits and stores the closest value it can. Tiny errors appear, and arithmetic can make them grow.
print(0.1 + 0.2) # 0.30000000000000004
print(0.1 + 0.2 == 0.3) # False
import math
print(math.isclose(0.1 + 0.2, 0.3)) # TrueRules for comparing
Never test floating-point results for exact equality. Compare with an absolute or relative tolerance that fits your domain, using a helper such as math.isclose.
Big and small do not mix
Adding a very small number to a very large one can lose the small part completely, and subtracting nearly equal numbers loses precision. Summing a long list in a different order can change the result slightly. For long accumulations, use algorithms made for it, such as compensated (Kahan) summation, or a library function designed for accurate sums.
Special values
IEEE 754 defines infinity and NaN (not a number). NaN is not equal to anything, including itself, so check for it with a dedicated function.
import math
nan = float("nan")
print(nan == nan) # False
print(math.isnan(nan)) # TrueMoney
Do not use binary floating point for currency. Two safe options:
- Integers in the smallest unit: store 1999 cents instead of 19.99 dollars. Addition and comparison are exact. Convert to a display string only at the edge.
- Decimal types that work in base 10, such as
Decimalin Python ornumericin SQL, with an explicit rounding rule.
from decimal import Decimal, ROUND_HALF_UP
price = Decimal("19.99")
total = (price * 3).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
print(total) # 59.97Decide the rounding mode and the point of rounding, such as per line or per invoice, because different choices give different totals.
Takeaway
Floating point is an approximation made for speed. Compare with tolerance, expect NaN and infinity, and keep money in integers or decimals.
Comments