64 Bits of Precision

Why doesn't 0.1 + 0.2 equal 0.3? The answer lies in how the computer stores fractional numbers in binary (the IEEE 754 standard).

1. The Binary Fraction Problem

A computer cannot store infinite fractions. For example, 0.1 in binary becomes an infinite fraction 0.0001100110011.... The browser is forced to cut it off, leading to a microscopic loss of precision.

2. Safe Integers

For integers, there is a " safe range " : ±(2^53 - 1). Anything beyond that will require the BigInt type.

3. How to Live with It?

  1. Round on output: +sum.toFixed(2).
  2. Work with integers: Store prices in cents (30 cents instead of 0.3 dollars), and convert back to dollars only when displaying to the user.
Tip

JS has a built-in constant Number.EPSILON — the minimum difference between two representable numbers. If the difference between 0.1 + 0.2 and 0.3 is less than this constant, they can be considered equal.

Caution

Never compare floating-point numbers directly (==) in critical logic (finance, space). Use rounding or tolerances.