JavaScript Floating-Point Precision and Approximate Equality
Quick answer
JavaScript Number uses binary64 floating-point arithmetic. Many decimal fractions cannot be represented exactly in binary, so arithmetic may round the mathematical result.
How it works
For finite approximate measurements, compare an absolute difference against a tolerance chosen for the problem. Number.EPSILON is the gap from 1 to the next larger representable number; it is not a universal error tolerance. At large magnitudes spacing grows. For exact bounded decimal quantities such as money, consider integer minor units.
const sum = 0.1 + 0.2;console.log(sum, sum === 0.3);Expected output in Node.js:
0.30000000000000004 falseBinary representations round the sum.
console.log(Math.abs((0.1+0.2)-0.3) < 1e-9);console.log(1 + Number.EPSILON > 1);Expected output in Node.js:
truetrueThe first test uses a chosen tolerance; EPSILON changes 1.
Common mistakes
Do not use exact equality for arbitrary approximate computations, or assume rounding the display repairs stored numerical error.
Practice
Compare two computed decimal readings with a justified tolerance.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript Floating-Point Precision and Approximate Equality — Knowledge Check
Apply the taught concept and predict the output.
When decimal fractions such as one tenth are stored as binary64 Numbers, which mechanism can make a later sum differ from the mathematical result?
What does Number.EPSILON describe?
What should determine a tolerance for comparing approximate readings?
What is the exact console output in JavaScript Floating-Point Precision and Approximate Equality example 1?
const sum = 0.1 + 0.2;console.log(sum, sum === 0.3);What is the exact console output in JavaScript Floating-Point Precision and Approximate Equality example 2?
console.log(Math.abs((0.1+0.2)-0.3) < 1e-9);console.log(1 + Number.EPSILON > 1);