Why 0.1 + 0.2 !== 0.3 in JavaScript: Floating-Point Precision, Rounding and Money
The most famous JavaScript puzzle, explained properly: how 0.1 is stored in binary, why errors appear and accumulate, how to compare decimals with a tolerance, toFixed's surprises, Math.sumPrecise, and the right way to handle money with integer cents, BigInt and Intl.NumberFormat.
kvi5hnuCode Sprout team member9 min readOn this page
Type 0.1 + 0.2 into any JavaScript console and you get 0.30000000000000004. This is probably the most-shared JavaScript "wat", and the most common interview warm-up about numbers. It isn't a JavaScript bug: Python, Java, C# and C give exactly the same answer with their double type. Once you understand why, you'll know when floating point is perfectly fine and when (money!) you need a different approach.
The symptom
console.log(0.1 + 0.2);
console.log(0.1 + 0.2 === 0.3);
console.log(0.3 - 0.2); // not 0.1
console.log(0.2 - 0.1); // happens to be exact
console.log(19.99 * 100); // converting dollars to cents
let total = 0;
for (let i = 0; i < 10; i++) total += 0.1;
console.log(total); // ten dimes are not quite a dollar
0.30000000000000004
false
0.09999999999999998
0.1
1998.9999999999998
0.9999999999999999
Why it happens
A JavaScript number stores a value in binary: a sign, an exponent and 52 bits of fraction (article 10). Binary fractions can represent exactly the values whose denominator is a power of two: 1/2, 1/4, 3/8, 5/1024. But 1/10 in binary is a repeating fraction, 0.000110011001100110011... forever, just as 1/3 is 0.333... forever in decimal.
With only 52 bits available, the pattern has to be cut off and rounded. So the literal 0.1 in your code becomes the double closest to 0.1, which is very slightly larger:

console.log((0.1).toPrecision(25));
console.log((0.2).toPrecision(25));
console.log((0.3).toPrecision(25));
console.log((0.1 + 0.2).toPrecision(25));
console.log((0.1).toString(2)); // the binary digits
0.1000000000000000055511151
0.2000000000000000111022302
0.2999999999999999888977698
0.3000000000000000444089210
0.0001100110011001100110011001100110011001100110011001101
Now the puzzle is clear:
0.1is stored a bit above 0.1, and0.2a bit above 0.2.- Their sum is a bit above 0.3, and it rounds to the double just above 0.3.
- The literal
0.3is stored as the double just below 0.3. - Those are two different doubles, so
===is false.
Why does console.log(0.1) print 0.1, then? When converting a number to a string, JavaScript prints the shortest decimal that converts back to exactly the same double. For the stored value of 0.1, that's "0.1". For the sum, no short decimal identifies it, so you see all 17 digits: 0.30000000000000004.
How big are the errors?
Tiny. A double has about 15 to 17 significant digits of precision, so the relative error of one operation is at most about 1 part in 9 quadrillion (2^-53). For physics, graphics, statistics, sensor readings and almost all scientific work, that's far more precision than the data has.
The problems come from three situations:
- Exact comparison with
===of computed decimals. - Accumulation: errors add up over millions of operations, or when adding numbers of very different sizes.
- Money and other exact decimal quantities, where a single wrong cent matters and auditors expect exact results.
Accumulation and cancellation
Adding a small number to a huge one can lose it completely:
console.log(1e16 + 1); // 1 is smaller than the gap between doubles here
console.log(1e20 + 1 - 1e20); // the 1 vanished
console.log([1e20, 1, -1e20].reduce((sum, x) => sum + x, 0));
10000000000000000
0
0
The gap between neighboring doubles grows with their size: near 1 it's about 2.2 × 10^-16 (Number.EPSILON), near 10^16 it's 2. For long sums, two fixes exist:
- Add numbers in a sensible order (smallest magnitudes first), or use an algorithm such as Kahan summation.
Math.sumPrecise(iterable)(ES2026) computes the exact sum of all the values and rounds only once at the end. It's newer than many runtimes (Node.js 25, for example, doesn't have it), so check support before relying on it:
Math.sumPrecise([1e20, 1, -1e20]); // 1
Math.sumPrecise([0.1, 0.2]); // 0.30000000000000004
The second line shows its limit: it removes accumulated error, but 0.1 and 0.2 are still the slightly-off doubles, so their exact sum still rounds to 0.30000000000000004.
Comparing decimals: use a tolerance
Instead of asking "are these equal?", ask "are these close enough?":
function nearlyEqual(a, b, relTol = 1e-9, absTol = 1e-12) {
const diff = Math.abs(a - b);
return diff <= absTol || diff <= relTol * Math.max(Math.abs(a), Math.abs(b));
}
console.log(nearlyEqual(0.1 + 0.2, 0.3));
console.log(nearlyEqual(1e20 + 1e4, 1e20)); // relative: these are close
console.log(nearlyEqual(0.001, 0.002)); // relative: these are not
console.log(Math.abs(0.1 + 0.2 - 0.3) < Number.EPSILON); // the common shortcut
true
true
false
true
You'll often see Math.abs(a - b) < Number.EPSILON. It works for values around 1, but it's too strict for large numbers (where the gap between doubles is far bigger than EPSILON) and too loose for tiny ones. A relative tolerance, scaled by the size of the values, plus a small absolute tolerance for values near zero, is the robust version. Pick tolerances that suit your data; the defaults above match Python's math.isclose.
Test frameworks do this for you: Jest and Vitest have expect(x).toBeCloseTo(0.3). With Node's built-in test runner, use a helper like the one above.
Rounding for display: toFixed and its surprises
number.toFixed(digits) returns a string with exactly that many decimal places. It's for display; convert back with Number(...) or unary + if you need a number.
console.log((0.1 + 0.2).toFixed(2)); // a string
console.log(+(0.1 + 0.2).toFixed(2)); // back to a number
console.log((2.5).toFixed(0), (3.5).toFixed(0)); // exact halves round up
console.log((1.005).toFixed(2)); // looks like a half, but isn't
console.log((1.45).toFixed(1), (8.345).toFixed(2));
0.30
0.3
3 4
1.00
1.4 8.35
The "inconsistent" results all have the same cause. 1.005 is stored as 1.00499999999999989..., which is below the halfway point, so it rounds down. 1.45 is stored just below 1.45 and rounds down; 8.345 is stored just above 8.345 and rounds up. toFixed rounds the stored value correctly; the stored value just isn't what you typed.
For user-facing output, prefer Intl.NumberFormat (or toLocaleString), which also adds grouping separators and currency symbols for the user's locale:
const usd = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" });
const inr = new Intl.NumberFormat("en-IN", { style: "currency", currency: "INR" });
console.log(usd.format(1234.5));
console.log(inr.format(1234567.891)); // Indian digit grouping
console.log(usd.format(-0.004)); // rounds to a negative zero amount
const evenRounding = new Intl.NumberFormat("en-US", {
maximumFractionDigits: 0,
roundingMode: "halfEven", // "banker's rounding"
});
console.log(evenRounding.format(2.5), evenRounding.format(3.5));
$1,234.50
₹12,34,567.89
-$0.00
2 4
roundingMode (ES2023's Intl additions) supports "halfExpand" (the default: halves away from zero), "halfEven" (banker's rounding, which avoids an upward bias in large totals), "ceil", "floor", "trunc" and more. Note the -$0.00: add signDisplay: "negative" to hide the sign of values that round to zero.
Money: the right way
Never store money as floating-point dollars and add them up. The standard approaches:
1. Integer minor units (cents)
Store every amount as an integer count of the smallest unit: cents for dollars and euros, paise for rupees, and so on. Integer addition and subtraction are exact up to 2^53 - 1, which is about 90 trillion dollars in cents.
const cart = [
{ item: "Notebook", priceCents: 1999, qty: 2 },
{ item: "Pen", priceCents: 149, qty: 3 },
];
const subtotal = cart.reduce((sum, line) => sum + line.priceCents * line.qty, 0);
const taxRate = 0.0825; // 8.25%
const tax = Math.round(subtotal * taxRate); // round once, to a whole cent
const total = subtotal + tax;
const fmt = cents => (cents / 100).toLocaleString("en-US", { style: "currency", currency: "USD" });
console.log("Subtotal:", fmt(subtotal));
console.log("Tax: ", fmt(tax));
console.log("Total: ", fmt(total));
Subtotal: $44.45
Tax: $3.67
Total: $48.12
Rules that keep this correct:
- Convert at the edges. Parse user input like
"19.99"into cents once, as text, not withparseFloat("19.99") * 100(which gives 1998.9999999999998). Splitting the string on"."or usingMath.round(parseFloat(s) * 100)both work for normal prices. - Round once, deliberately, when a calculation (tax, discount, interest, currency conversion) produces a fraction of a cent, and decide the rounding rule with whoever owns the business logic.
- Division needs a remainder plan. Splitting $100.00 three ways gives 3333 + 3333 + 3334 cents; someone gets the extra cent.
- Not every currency has 2 decimals: the Japanese yen has 0 and the Bahraini dinar has 3.
new Intl.NumberFormat("en", { style: "currency", currency: "BHD" }).resolvedOptions().maximumFractionDigitstells you.
2. BigInt for very large or precise amounts
For values beyond 2^53, such as cryptocurrency balances in their smallest unit, use bigint integers (article 13), which have no size limit.
3. A decimal library
For complex financial math (interest, currency conversion with many decimal places, percentages of percentages), use a decimal arithmetic library such as decimal.js, big.js or dinero.js. They store numbers in base 10, so 0.1 + 0.2 is exactly 0.3. A built-in decimal type has been proposed in TC39, but it isn't part of the language today.
Common questions
Is this a JavaScript bug?
No. It's how IEEE 754 binary floating point works, and nearly every language uses it. In Python, 0.1 + 0.2 prints 0.30000000000000004 too. Languages that seem immune either show fewer digits when printing or use a decimal type for that literal.
Which decimal fractions are exact?
Those whose denominator, in lowest terms, is a power of 2: 0.5, 0.25, 0.125, 0.75, 0.375. So 0.5 + 0.25 === 0.75 is true. Most decimals with 1 or 2 places (0.1, 0.2, 0.3, 0.7, 0.01...) are not exact.
Are integers affected?
Not within the safe range: integer arithmetic on numbers up to 2^53 - 1 is exact, as long as the results stay in range and you don't divide. That's why storing money in cents works.
Why not just round everything with toFixed?
toFixed returns a string, rounds the stored (slightly off) value, and rounding at every step can accumulate its own errors. Round once, at the point your business rules say, and format only for display.
Can I make 0.1 + 0.2 === 0.3 true?
Not with numbers. Options: compare with a tolerance, compare after rounding to a fixed number of places ((0.1 + 0.2).toFixed(2) === (0.3).toFixed(2)), work in integers (1 + 2 === 3 tenths), or use a decimal library.
Summary
- Numbers are binary; most decimal fractions (0.1, 0.2, 0.3) are stored as the nearest double, very slightly off.
0.1 + 0.2is the double just above 0.3, while0.3is the double just below, so===fails. Printing shows the shortest round-tripping decimal.- Compare computed decimals with a relative tolerance, not
===.Number.EPSILONalone only suits values near 1. - Errors accumulate and small values vanish next to big ones;
Math.sumPrecise(ES2026) sums exactly. toFixedreturns a string and rounds the stored value ((1.005).toFixed(2)is"1.00"). UseIntl.NumberFormatfor display, withroundingModeif needed.- Money: integer minor units, round once deliberately,
bigintfor huge values, or a decimal library.
Practice Questions
What does 0.1 * 3 === 0.3 evaluate to?
Answer
false. 0.1 * 3 is 0.30000000000000004.
Is 0.5 + 0.25 === 0.75 true or false? Why?
Answer
true. 0.5, 0.25 and 0.75 have power-of-two denominators (1/2, 1/4, 3/4), so they're stored exactly and their sum is exact.
Why does parseFloat("4.35") * 100 give 434.99999999999994, and how do you get 435 cents?
Answer
4.35 is stored just below 4.35, and multiplying keeps the error. Use Math.round(parseFloat("4.35") * 100), which gives 435, or parse the string's whole and fractional parts as integers.
Split 1000 cents fairly among 3 people so the shares add up to exactly 1000.
Answer
Math.floor(1000 / 3) is 333 for everyone, with a remainder of 1000 % 3 = 1 cent. Give the extra cent to one person: 334, 333, 333.
Why is Math.abs(a - b) < Number.EPSILON a poor equality test for a = 1e10 + 0.1 + 0.2 and b = 1e10 + 0.3?
Answer
Near 10^10, neighboring doubles are about 2 × 10^-6 apart, far larger than EPSILON (2.2 × 10^-16). Any rounding difference at all will exceed EPSILON, so values that are "equal for practical purposes" are reported as different. A relative tolerance scales with the size of the values.
Previous: Infinity, NaN and Negative Zero in JavaScript: Special Number Values Explained
Next: JavaScript BigInt: Arbitrary-Precision Integers, Operators and Pitfalls

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.