Number.EPSILON
The smallest difference between 1 and the next number — for comparing fractions.
Available since: ES2015
Syntax
Number.EPSILONReturn value
numberA very small number, about 2.2e-16.
Examples
Why 0.1 + 0.2 is not 0.3:
console.log(0.1 + 0.2);
console.log(0.1 + 0.2 === 0.3);Output:
0.30000000000000004
falseComparing with a tolerance:
const equal = (a, b) => Math.abs(a - b) < Number.EPSILON;
console.log(equal(0.1 + 0.2, 0.3));Output:
trueNotes
Fractions are stored in binary, where many decimal fractions are inexact. So fractions are compared with a tolerance, and money is kept in cents as integers.
See also
- Number.prototype.toFixed — Formats a number with a given number of decimal places.
- Math.abs — Returns the absolute value of a number — its value without the sign.
- Math.round — Rounds a number to the nearest integer.
Related recipes
In the tutorial
- Numbers — Numbers in JavaScript — integers and fractions, rounding, the Math object, toFixed and the special values Infinity and NaN.