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?
- Round on output:
+sum.toFixed(2). - Work with integers: Store prices in cents (
30cents instead of0.3dollars), and convert back to dollars only when displaying to the user.
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.
Never compare floating-point numbers directly (==) in critical logic (finance, space). Use rounding or tolerances.