Why? JavaScript can't store decimal numbers exactly. It's like trying to write 1/3 as a decimal - you get 0.333333... forever. JavaScript stores 0.1 as something like 0.10000000000000001. The Cheat Code: Never use === for decimal comparisons. Use tolerance checking instead: Math.abs(a - b) < 0.0001.
Average 5.0 by 2 learners
console.log(0.1 + 0.2); // 0.30000000000000004
console.log(0.1 + 0.2 === 0.3); // false 😱
Wait, what?! Math is broken in JavaScript? Not quite - but close enough to ruin your day!
🎯 The Real Culprit: IEEE 754 Binary Floating-Point Standard
Think of it like this:
Some decimal numbers can't be perfectly represented in binary, just like 1/3 can't be perfectly written as a decimal (0.333333... forever).
// What we think happens:
0.1 + 0.2 = 0.3 ✅
// What actually happens in binary:
0.1 → 0.0001100110011001100110011001100110011... (infinite!)
0.2 → 0.0011001100110011001100110011001100110011... (infinite!)
Sum → 0.30000000000000004 ❌
It's like trying to fit an infinite number into a finite box !
When you perform 0.1 + 0.2 in JavaScript, the internal representation of these approximations are added together. The result is not exactly 0.3, but a value very, very close to it, such as 0.30000000000000004. Because of this tiny discrepancy, a strict equality comparison (===) with 0.3 will fail.
function isEqual(a, b) {
return a === b;
}
console.log(isEqual(0.1 + 0.2, 0.3)); // false
// Your calculator app is "broken"!
let balance = 0.1;
balance += 0.2;
if (balance === 0.3) {
console.log("Transaction approved");
} else {
console.log("Error: Invalid amount"); // This runs instead! 💥
}
To mitigate this problem, especially when comparing floating-point numbers, you should avoid using strict equality (===) directly. Instead, employ a tolerance check or a threshold value (often called an epsilon`).
This involves checking if the absolute difference between the two numbers is less than a very small predefined value.
function isFloatEqual(a, b, tolerance = 0.0001) {
return Math.abs(a - b) < tolerance;
}
console.log(isFloatEqual(0.1 + 0.2, 0.3)); // true ✅
console.log(isFloatEqual(0.1 + 0.2, 0.3, 0.00001)); // true ✅
function isEqual(a, b) {
return Math.abs(a - b) < Number.EPSILON;
}
console.log(isEqual(0.1 + 0.2, 0.3)); // true ✅
🧠 Remember: "Floats float away from accuracy"
🎯 Rule: Never use === with decimal numbers in JavaScript 💡
Solution: Always use tolerance when comparing floats
It's not a bug, it's a feature! 😅 (Actually, it's just how computers work)
Understanding these nuances of floating-point arithmetic is crucial for writing robust and accurate JavaScript applications, especially when dealing with numerical data.