Sub topic 4
Why 0.1 + 0.2 !== 0.3 and How to Compare Floats
This chapter assumes you know basic JavaScript syntax, can run code in Node.js or a browser console, and understand ===. It builds on the earlier chapter about how every Number is a 64-bit IEEE 754 double. Here you will see why some decimal arithmetic comes out slightly wrong, where the error comes from, and how to compare results without being caught by it.
The Symptom
Run this in any JavaScript engine:
console.log(0.1 + 0.2); // 0.30000000000000004
console.log(0.1 + 0.2 === 0.3); // false
console.log(1.1 + 2.2); // 3.3000000000000003
let total = 0;
for (let i = 0; i < 10; i++) total += 0.1;
console.log(total); // 0.9999999999999999The engine has no bug here. Every language that uses binary floating point does the same thing, including Python, Java, C, and Go. JavaScript just makes it easier to notice, because the Number type is the only number type most code ever touches.
Where the Error Comes From
Decimal fractions that binary cannot represent
A double stores a value as a binary fraction times a power of two. A fraction has an exact binary form only when its denominator, in lowest terms, is a power of two. 0.5 is 1/2, and 0.375 is 3/8, so both are exact. 0.1 is 1/10, and 10 has a factor of 5. In binary it repeats forever, the same way 1/3 repeats in decimal:
0.1 (decimal) = 0.0001100110011001100110011... (binary, repeating)A double holds 53 significant bits, so the engine cuts that pattern off and rounds to the nearest double it can represent. You can see the stored value by asking for more digits than JavaScript normally shows:
console.log((0.1).toFixed(20)); // "0.10000000000000000555"
console.log((0.2).toFixed(20)); // "0.20000000000000001110"
console.log((0.3).toFixed(20)); // "0.29999999999999998890"The stored 0.1 is a little above one tenth, and so is the stored 0.2. The stored 0.3 is a little below three tenths.
Rounding happens again after every operation
IEEE 754 requires each +, -, *, and / to give the exact result of the operation rounded to the nearest representable double. The exact sum of the stored 0.1 and the stored 0.2 falls between two neighboring doubles. Rounding picks the upper one, 0.30000000000000004. That is a different double from the one the literal 0.3 produces, so === returns false.
Why 0.1 prints as "0.1"
If 0.1 is stored inexactly, why does console.log(0.1) print 0.1? When JavaScript converts a Number to a string, it prints the shortest decimal string that maps back to the same double. "0.1" is enough to identify the stored value, so that is what you see. The sum lands on a different double, and the shortest string that identifies that double is 0.30000000000000004. The display hides representation error until an operation moves the value onto a different double.
Comparing With a Tolerance
Do not ask whether two computed floats are identical. Ask whether they are close enough. The usual starting point is Number.EPSILON:
console.log(Number.EPSILON); // 2.220446049250313e-16 (that is, 2 ** -52)
function nearlyEqual(a, b, epsilon = Number.EPSILON) {
return Math.abs(a - b) < epsilon;
}
console.log(nearlyEqual(0.1 + 0.2, 0.3)); // true
console.log(nearlyEqual(1.1 + 2.2, 3.3)); // falseThe gotcha: Number.EPSILON is an absolute threshold
Number.EPSILON is the gap between 1 and the next larger double. Near 1 it is a reasonable tolerance. The gap between neighboring doubles grows with the size of the number, though. Between 2 and 4 it is 2 * Number.EPSILON, and for large values it is far bigger. Once both values are at least 2, any two different doubles are already more than Number.EPSILON apart, so nearlyEqual behaves exactly like ===. That is why 1.1 + 2.2 fails above.
A relative tolerance
A more reliable check scales the tolerance with the size of the operands and adds an optional absolute floor for values near zero. Python's math.isclose works the same way.
function approxEqual(a, b, relTol = 1e-9, absTol = 0) {
if (a === b) return true; // exact match, including equal infinities
if (!Number.isFinite(a) || !Number.isFinite(b)) return false; // NaN or mismatched infinity
const diff = Math.abs(a - b);
const scale = Math.max(Math.abs(a), Math.abs(b));
return diff <= Math.max(relTol * scale, absTol);
}
console.log(approxEqual(0.1 + 0.2, 0.3)); // true
console.log(approxEqual(1.1 + 2.2, 3.3)); // true
console.log(approxEqual(1e20 + 1e4, 1e20)); // true
console.log(approxEqual(0.1 + 0.2 - 0.3, 0)); // false: relative test fails near 0
console.log(approxEqual(0.1 + 0.2 - 0.3, 0, 1e-9, 1e-12)); // true with an absolute floor
console.log(approxEqual(NaN, NaN)); // false
console.log(approxEqual(Infinity, 1e308)); // falseEdge cases this version handles
| Case | Problem with a naive check | How `approxEqual` handles it | Column | Column | Column | Column |
|---|---|---|---|---|---|---|
| Large magnitudes | A fixed epsilon is smaller than the gap between doubles | Tolerance scales with `Math.max( | a | , | b | )` |
| Comparing to zero | Relative tolerance times 0 is 0 | `absTol` sets a minimum allowed difference | ||||
| `NaN` inputs | `Math.abs(NaN)` comparisons are always false, which is fine but implicit | Rejected explicitly by `Number.isFinite` | ||||
| `Infinity` vs a large finite value | `Infinity <= Infinity` makes the naive relative check return true | Non-finite values are rejected unless identical | ||||
| `Infinity === Infinity` | The difference would be `NaN` | Caught by the early `a === b` check |
Choosing tolerances
There is no universal tolerance. Pick one from the problem you are solving:
- Measured or physical quantities: a relative tolerance matched to the precision of the measurements, such as
1e-6. - Results of a few arithmetic steps:
1e-9relative is usually safe, because a double carries about 15 to 17 significant decimal digits. - Values expected to be zero, such as the remainder of a cancellation: always set an
absTolbased on the size of the inputs that were subtracted. - Long loops that accumulate error: error grows with the number of operations, so loosen the tolerance or restructure the calculation.
Avoiding the Problem Instead of Tolerating It
Sometimes the better fix is to keep inexact fractions out of the calculation entirely.
// Money: store integer cents, convert only for display
const priceCents = 1999;
const taxCents = 160;
const totalCents = priceCents + taxCents; // 2159, exact
console.log((totalCents / 100).toFixed(2)); // "21.59"
// Loops: count with integers, derive the fraction each time
for (let i = 0; i <= 10; i++) {
const x = i / 10; // one rounding per value, no accumulation
if (i === 10) console.log(x); // 1
}Ordering comparisons such as < and > work correctly on doubles. Be careful only at boundaries: a value that should be exactly 0.3 might be stored as 0.30000000000000004 and fail a <= 0.3 check. Apply the same tolerance logic there: x <= 0.3 + tol.
Exercise
Why does nearlyEqual(1.1 + 2.2, 3.3) return false when it uses Number.EPSILON as an absolute tolerance, while nearlyEqual(0.1 + 0.2, 0.3) returns true?
Show answer
Number.EPSILON (2^-52) is the gap between doubles near 1. Near 3.3 the gap between neighboring doubles is 2^-51, which is larger than Number.EPSILON. Any two different doubles there differ by at least 2^-51, so the test only passes when the values are identical. The error in 0.1 + 0.2 is about 5.55e-17, which is below Number.EPSILON, so that case passes.
Exercise
A function computes a - b for two nearly equal measurements and checks whether the result is zero using approxEqual(result, 0) with the default arguments. It always returns false unless the result is exactly 0. What is wrong, and how do you fix it?
Show answer
With b = 0, the scale is |result|, so the allowed difference is relTol |result|. That is always smaller than |result| itself unless the result is exactly 0. Pass an absolute tolerance based on the size of the original inputs, for example `approxEqual(result, 0, 1e-9, 1e-9 Math.max(Math.abs(a), Math.abs(b)))`.
Exercise
Rewrite let sum = 0; for (let i = 0; i < 3; i++) sum += 0.10; so that adding three 10-cent items yields an exact total, and print it as "0.30".
Show answer
Work in integer cents: let cents = 0; for (let i = 0; i < 3; i++) cents += 10; console.log((cents / 100).toFixed(2)); This prints "0.30" because the integer additions are exact, and the single division and formatting happen only at display time.