Skip to content

Computing foundations · Part 9 of 10

Floating-point numbers: why 0.1 + 0.2 is not 0.3, and what to do about money

Binary floating point cannot represent most decimals exactly. Compare with a tolerance, and store money as integers or decimals.

· 2 min read

numbersdata

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.

Python
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))   # True

Rules 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.

Python
import math

nan = float("nan")
print(nan == nan)        # False
print(math.isnan(nan))   # True

Money

Do not use binary floating point for currency. Two safe options:

  1. 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.
  2. Decimal types that work in base 10, such as Decimal in Python or numeric in SQL, with an explicit rounding rule.
Python
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.97

Decide 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.

A knowledge article, drafted with AI assistance and checked with automated tests. It is general background, not a description of my own experience or of any client's work.

Comments

Leave a comment

No account or email needed. Comments appear after review. A one-way hash of your IP address is kept for 30 days to fight spam, then erased.