
0.1 + 0.2 !== 0.3 Isn't a JavaScript Bug: Floating-Point Numbers Explained
- كاتب موثّق
- ES2025
محتويات المقال
balance >= 1, and logging balance prints 0.9999999999999999. The bug report says "JavaScript can't add", and the fix in review is Number(balance.toFixed(2)) >= 1. It passes this test, and it leaves the real problem in place.
The common misconception
0.1 + 0.2 should simply be 0.3, and toFixed(2) is the standard way to clean up results, especially for money.
Number type for integers and fractions alike, so developers meet floating-point math on day one, while in many other languages they would reach for an integer or decimal type first. And toFixed(2) makes the screen look right, so it feels like a fix. The true part: JavaScript has no built-in decimal type, so you do need a strategy for money. But 0.30000000000000004 is correct floating-point arithmetic, and toFixed only changes how a number is printed.
What actually happens
Numbers are binary fractions
double in Java or C#. It has 1 sign bit, 11 exponent bits and 52 bits of fraction, which gives about 15 to 17 significant decimal digits. Integers are exact only up to 2^53 − 1, which is Number.MAX_SAFE_INTEGER.
0.1 has no exact binary form
Number.EPSILON page makes exactly this point: any format with a finite number of bits must leave most numbers out. So the literal 0.1 is stored as the nearest double, which is slightly above 0.1. The same happens to 0.2. Their sum is rounded to the nearest double again, and it lands on the double just above 0.3, while the literal 0.3 is stored just below it.
0.1 prints as 0.1 even though it isn't exactly 0.1. The sum needs 17 digits to be told apart from 0.3, so you see them all:
console.log(0.1 + 0.2); // 0.30000000000000004console.log((0.1).toFixed(20)); // 0.10000000000000000555console.log(0.1 + 0.2 === 0.3); // falseconsole.log(Math.abs(0.1 + 0.2 - 0.3) < Number.EPSILON); // true, near 1console.log(1000.1 + 1000.2); // 2000.3000000000002console.log(2 ** 53 + 1); // 9007199254740992: integers stop being exacttoFixed formats, it doesn't fix
toFixed(2) returns a string with the number rounded to two decimals. As a money fix it fails in three ways. It's a string, so + concatenates instead of adding. It rounds the stored binary value, not the decimal you typed: MDN shows (2.55).toFixed(1) returning "2.5", because the closest double to 2.55 is slightly below it. And converting the string back with Number() gives you a double again, so the next operation can drift again. It's the right tool at the very end, when you show a number to a person.
Tolerances are for measurements
Math.abs(a - b) < tolerance. MDN warns that Number.EPSILON only works as that tolerance for numbers around 1. Near 2000, the error in the line above is about 10^-13, far bigger than EPSILON, so choose a tolerance from the magnitude and the precision of your data. Money isn't approximate, though. It needs exact arithmetic.
Fixing the wallet
Number.MAX_SAFE_INTEGER, which is over 90 trillion pounds in piastres. The division by 100 happens once, for display:
let balance = 0;for (let order = 1; order <= 10; order++) { balance += 0.1; // 0.10 EGP cashback per order}console.log(balance); // 0.9999999999999999console.log(balance >= 1); // false: "Redeem 1 EGP" stays disabledconsole.log(balance.toFixed(2)); // 1.00, but it's a stringconsole.log((0.1).toFixed(2) + (0.2).toFixed(2)); // 0.100.20console.log((2.55).toFixed(1)); // 2.5: 2.55 is stored slightly belowlet balance = 0; // in piastres: 1 EGP = 100 piastresfor (let order = 1; order <= 10; order++) { balance += 10; // integers add exactly}console.log(balance >= 100); // trueconst egp = new Intl.NumberFormat("en-EG", { style: "currency", currency: "EGP",});console.log(egp.format(balance / 100)); // EGP 1.00=== on computed decimals | 0.1 + 0.2 === 0.3 is false | |
toFixed(2) | 2.55 gives "2.5" | |
Math.abs(a - b) < tol | EPSILON only fits values near 1 | |
MAX_SAFE_INTEGER, or switch to BigInt | ||
Intl.NumberFormat with a currency |
How to apply it in your project
Store money as integers Keep amounts in piastres or cents in state, storage and API payloads. Convert a two-decimal input once with Math.round(Number(text) * 100).Stop comparing computed decimals with === Compare integers, or use a tolerance that fits the magnitude and precision of the values. Format only at the edge Use Intl.NumberFormat, ortoFixedfor simple cases, right where a number becomes text on screen, never in the middle of a calculation.Own your rounding rule Put tax, discount and split rounding in one tested helper, so every screen and every invoice rounds the same way.
Key takeaways
JavaScript numbers are IEEE 754 doubles, the same format as doublein Java and C#, so0.1 + 0.2isn't a JavaScript bug.Most decimal fractions, like 0.1, have no exact binary form, so arithmetic on them carries tiny rounding errors. toFixedformats for display: it returns a string and rounds the stored binary value, so it isn't a money fix.For money, compute in integer minor units and format with Intl.NumberFormatat the end.For measurements, compare with a tolerance that matches the magnitude and precision of your data.
التعليقات (0)