Computers can't store most decimals exactly. A double packs a real number into
just 64 bits — one sign bit, an 11-bit exponent, and a 52-bit fraction — so values like
0.1 get rounded to the nearest number that does fit. That's why
0.1 + 0.2 famously isn't 0.3. Every number below is computed live with real
JavaScript doubles, so the discrepancies you see are genuine.
0.1 and 0.2 are clean in decimal, but in binary they're infinitely repeating fractions — like ⅓ = 0.333… in decimal. The CPU has to round each to the nearest value it can actually represent, and those tiny rounding errors add up. Type any two decimals and watch what really gets stored, then whether the sum exactly equals what you expected.
Why 0.5 + 0.25 is exact: both are sums of powers of two (½ and ¼), so they fit perfectly with no rounding — and their sum, 0.75, does too. The trouble is only with values binary can't terminate on.
Every double is 1 sign bit +
11 exponent bits + 52 mantissa (fraction) bits.
The value is reconstructed as (−1)sign × 1.mantissa × 2exponent−1023.
Click a bit to flip it, or pick an example. That's only ~15–17 significant decimal digits of precision.
The 2^53 wall: a double has 52 fraction bits, so the largest integer where
every whole number is still representable is 253 = 9,007,199,254,740,992. Beyond it,
integers start skipping — 2^53 + 1 rounds straight back down to 2^53.
(That's Number.MAX_SAFE_INTEGER territory.)
Because results carry tiny rounding errors, exact equality is a trap. Compare with a small tolerance (epsilon) instead: treat a and b as equal when |a − b| < ε. For money, sidestep floats entirely — count integer cents or use a decimal type. And watch how error accumulates when you sum the same float many times.
Accumulated error: add 0.1 to a running total N times and compare with the "expected" 0.1 × N. The gap grows as errors pile up.
| Don't | Do |
|---|---|
| if (a == b) | if (Math.abs(a-b) < EPSILON) |
| price = 0.1 + 0.2 // dollars | cents = 10 + 20 // integers, then /100 |
| total += 0.1 // ×1000 | total = 0.1 * 1000 // or sum cents |