Tolerance-based equality
Comparing calculated decimal results
JS Puzzles · Const
JavaScript numbers use IEEE 754 double-precision binary floating point, so decimal arithmetic can contain small representation errors. Compare results with a tolerance suited to their magnitude instead of relying on strict equality.
JavaScript Number values use IEEE 754 double-precision binary floating point. Because many decimal fractions cannot be represented exactly in that format, arithmetic may introduce small errors; the suitable comparison tolerance depends on the values' magnitude.
Number.EPSILONconst value = 0.1 + 0.2;
console.log(value); // 0.30000000000000004
const closeEnough = (a, b, tolerance = Number.EPSILON) =>
Math.abs(a - b) < tolerance;
console.log(closeEnough(value, 0.3)); // trueBinary floating-point arithmetic can produce a result slightly different from the intended decimal value, so compare values using an appropriate tolerance rather than strict equality.
Comparing calculated decimal results
Checking whether a result is close to an expected value near 1
Handling integer identifiers beyond the safe range
NumberNumber.EPSILONNumber.MAX_SAFE_INTEGERNumber.isSafeIntegerBigInt