Advertisement
Advanced JavaScript, Numbers, Math & BigInt

How do you correctly compare two floating-point numbers for 'close enough' equality?

Short answer

Instead of strict equality, check whether the absolute difference between the two numbers is smaller than a small tolerance (epsilon) value, since floating-point rounding means direct equality checks on computed results are unreliable.

Save JavaScript mock interview
Advertisement
AModel answer
Instead of strict equality, check whether the absolute difference between the two numbers is smaller than a small tolerance (epsilon) value, since floating-point rounding means direct equality checks on computed results are unreliable.
function nearlyEqual(a, b, epsilon = Number.EPSILON * 100) {
  return Math.abs(a - b) < epsilon;
}
nearlyEqual(0.1 + 0.2, 0.3); // true
Real-world example
Comparing computed totals in a financial or scientific calculation where exact equality checks would fail unpredictably.
Likely follow-ups
  • What is Number.EPSILON and what does it represent exactly?
Related topics