Compare floating-point numbers safely in JavaScript
Intermediate · 4 min read
Ask JavaScript whether 0.1 + 0.2 equals 0.3 and it says false. Prices, measurements, game physics and chart axes all produce numbers like these, so any time you compare two decimals you need a safer test than ===.
In this tutorial you will write nearly(a, b), a comparison that treats two numbers as equal when they are close enough. Along the way you will see why a single fixed "close enough" stops working for very large numbers. You need to know what a function is and what Math.abs does (it removes the minus sign from a number).
Why decimals don't add up exactly
JavaScript stores numbers in binary, as sums of halves, quarters, eighths and so on. Most decimals, like 0.1, can't be written exactly that way, so the computer stores the closest value it can. Add two of those tiny errors together and the result is a hair away from what you expected:
console.log(0.1 + 0.2); // 0.30000000000000004
console.log(0.1 + 0.2 === 0.3); // false
The gap is far too small to matter in a price or a length. It only matters because === demands the two numbers be identical.
The idea: allow a tolerance
Instead of asking "are these the same?", ask "is the distance between them small?". The distance is Math.abs(a - b), and the allowed distance is called the tolerance:
console.log(Math.abs((0.1 + 0.2) - 0.3)); // 5.551115123125783e-17
The e-17 means "times 10 to the power -17", so that is a tiny number. Anything below the tolerance counts as equal.
Here is the exercise. Try it on your own first if you like, or read on and we will build it together.
62 Comparing two floats with a tolerance
fairWrite a comparison that treats 0.1 + 0.2 and 0.3 as equal, without treating 1 and 1.1 as equal. Explain why a fixed tolerance is not enough on its own.
Stuck? Three hints, smallest first
- 1.
Math.abs(a - b) < toleranceis the shape of it. - 2.
Number.EPSILONis the gap between 1 and the next representable number — it is only the right tolerance near 1. - 3. Scale the tolerance by the size of the values being compared, and you have a relative comparison.
Step 1: a fixed tolerance
JavaScript gives you a built-in tiny number, Number.EPSILON. It is the gap between 1 and the next number JavaScript can store just above 1. A few of those make a reasonable tolerance for numbers near 1:
const closeAbs = (a, b, tol = Number.EPSILON * 4) => Math.abs(a - b) <= tol;
console.log(Number.EPSILON); // 2.220446049250313e-16
console.log(closeAbs(0.1 + 0.2, 0.3)); // true
console.log(closeAbs(1, 1.1)); // false
tol = Number.EPSILON * 4 is a default parameter: if you don't pass a third argument, the function uses that value. The test treats 0.1 + 0.2 and 0.3 as equal, but still sees that 1 and 1.1 are different. That is what the exercise asks for, and for small numbers it is enough.
The name "abs" here is short for absolute: the tolerance is one fixed size, whatever numbers you compare.
Step 2: watch it break on big numbers
The gaps between stored numbers grow as the numbers grow. Past 2 to the power 53 (about 9 million billion), JavaScript can't even store every whole number:
console.log(2 ** 53 + 1 === 2 ** 53); // true: the +1 was lost
console.log(1e16 + 1 === 1e16); // true
Up there, the nearest neighbor of a number is 2 away. Two values that differ by a single rounding step are 2 apart, and a tolerance of a few EPSILON can never cover that:
const closeAbs = (a, b, tol = Number.EPSILON * 4) => Math.abs(a - b) <= tol;
console.log(closeAbs(2 ** 53, 2 ** 53 + 2)); // false
This is the trap. EPSILON is often described as "the smallest difference JavaScript can see", but it is only the gap near 1.
Step 3: let the tolerance grow with the numbers
A relative tolerance fixes this. Multiply the tolerance by the size of the bigger number, so comparing millions allows a bigger gap than comparing tenths:
const nearly = (a, b, tol = 1e-9) =>
Math.abs(a - b) <= tol * Math.max(1, Math.abs(a), Math.abs(b));
console.log(nearly(0.1 + 0.2, 0.3)); // true
console.log(nearly(1, 1.1)); // false
console.log(nearly(2 ** 53, 2 ** 53 + 2)); // true
console.log(nearly(0, 0)); // true
1e-9 means one billionth. Read the right-hand side as "one billionth of the size of these numbers". For 2 ** 53 that is about 9 million, so a gap of 2 is well inside.
Step 4: why the 1 is in Math.max
Math.max(1, Math.abs(a), Math.abs(b)) never lets the scale drop below 1. Without that 1, comparing two numbers close to zero would multiply the tolerance by something tiny, and you would be back to demanding an exact match:
const strict = (a, b, tol = 1e-9) =>
Math.abs(a - b) <= tol * Math.max(Math.abs(a), Math.abs(b));
console.log(strict(1e-20, 2e-20)); // false
const nearly = (a, b, tol = 1e-9) =>
Math.abs(a - b) <= tol * Math.max(1, Math.abs(a), Math.abs(b));
console.log(nearly(1e-20, 2e-20)); // true
With the 1 in place, small numbers fall back to a plain one-billionth tolerance. Test frameworks use the same idea in helpers like toBeCloseTo.
The full solution
The answer panel has both comparisons, prints the failing === check and EPSILON, and its checks cover numbers near 1, 1 against 1.1, and the large numbers past 2 to the power 53. Press Run to see the output.
// Absolute tolerance: fine for numbers near 1, useless for very large ones.
const closeAbs = (a, b, tol = Number.EPSILON * 4) => Math.abs(a - b) <= tol;
// Relative tolerance: the allowance grows with the magnitude of the inputs.
const nearly = (a, b, tol = 1e-9) =>
Math.abs(a - b) <= tol * Math.max(1, Math.abs(a), Math.abs(b));
console.log('0.1 + 0.2 === 0.3 ?', 0.1 + 0.2 === 0.3);
console.log('nearly(0.1 + 0.2, 0.3) ?', nearly(0.1 + 0.2, 0.3));
console.log('EPSILON is', Number.EPSILON);
console.log('1e16 + 1 === 1e16 ?', 1e16 + 1 === 1e16, '<- the gap is bigger than 1 up there');
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('the naive comparison fails', 0.1 + 0.2 === 0.3, false);
test('an absolute epsilon rescues it near 1', closeAbs(0.1 + 0.2, 0.3), true);
test('the relative version agrees', nearly(0.1 + 0.2, 0.3), true);
test('and neither claims 1 and 1.1 are the same', [closeAbs(1, 1.1), nearly(1, 1.1)], [false, false]);
test('EPSILON is exactly 2 to the power -52', Number.EPSILON === 2 ** -52, true);
test('past 2**53 whole numbers thin out', 2 ** 53 + 1 === 2 ** 53, true);
test('so an absolute epsilon is meaningless up there', closeAbs(2 ** 53, 2 ** 53 + 2), false);
test('while the relative one scales with the values', nearly(2 ** 53, 2 ** 53 + 2), true);
test('a value is always nearly itself', nearly(0, 0), true);
Number.EPSILON is often described as "the smallest difference JavaScript can see", which is wrong and leads to the bug in the seventh assertion. It is the gap to the next number after 1. Around 2⁵³ that gap is 2, so an absolute tolerance of 2⁻⁵² can never be met and two numbers that differ by a rounding error are reported as different.
Scaling the tolerance by the larger magnitude fixes it, which is what every test framework's toBeCloseTo does underneath. The Math.max(1, ...) in there matters too: without it, comparing values near zero would demand exactness.
Common mistakes
- Comparing decimals with
===. It works for whole numbers and fails for many sums of decimals, so the bug only shows up with some inputs. - Using
Number.EPSILONas the tolerance for every number. It is the gap next to 1. For large numbers it is far too strict. - Picking a tolerance that is too loose. A tolerance of
0.5would call1and1.1equal. Choose one much smaller than any difference you care about.
Try it yourself
- Use
nearlyto check that0.1 * 3is close to0.3, and print what0.1 * 3really is. - Add a third parameter to a call so
nearly(100, 100.5, 0.01)returnstrue. Work out why it does. - Write
isZero(x)that returnstruewhenxis within one billionth of zero, usingnearly.