Epsilon and Safe Comparison
You'll learn how to compare floating-point numbers correctly using Number.EPSILON to avoid precision errors.
The Problem with Direct Comparison
You already know why 0.1 + 0.2 !== 0.3 — floating-point representation creates tiny rounding errors. But how do you check if two numbers are "close enough" to be considered equal? That's where Number.EPSILON comes in.
What Is Number.EPSILON?
Number.EPSILON is the smallest difference JavaScript can represent between two numbers greater than 1. Its value is approximately 2.220446049250313e-16 — incredibly tiny! It represents the machine's precision limit.
Safe Comparison Technique
Instead of checking exact equality, check if the difference between two numbers is smaller than Number.EPSILON:
function safeEqual(a, b) {
return Math.abs(a - b) < Number.EPSILON;
}
console.log(0.1 + 0.2 === 0.3); // false
console.log(safeEqual(0.1 + 0.2, 0.3)); // true
Think of it like measuring with a ruler: If two lengths differ by less than your ruler's smallest mark, you consider them equal for practical purposes.
Why This Works
Math.abs(a - b) gives the absolute difference between the numbers. If that difference is smaller than the machine's precision threshold (Number.EPSILON), the numbers are "equal enough" — any difference is just rounding error, not a meaningful distinction.
Key Takeaway: Use Number.EPSILON with a tolerance check (Math.abs(a - b) < Number.EPSILON) to safely compare floating-point numbers that should be equal but aren't due to precision limits.