Skip to content
jshacks.dev
Fundamentals

Why 0.1 Plus 0.2 Is Not 0.3 in JavaScript and How to Cope

0.1 plus 0.2 gives 0.30000000000000004 because binary floating point cannot store 0.1 exactly. See the cause, a safe comparison and how to handle money.

6 min read
Summarize in AI
Flat illustration of an editor window full of code, with the JavaScript, TypeScript, Vite and npm logos.

0.1 + 0.2 === 0.3 is false in JavaScript, and in Python, Java, C, Go and every other language that uses the same hardware numbers. The result is not a bug and not a quirk of one language. It is a fact about writing tenths in base two, and once you see it, you can predict every surprising result of this kind and choose the right fix for your situation, which is different for a price, a physics value and a progress bar. This post shows the cause with real output on Node.js 24, a safe comparison, why toFixed() rounds the way it does and how to store money. The format itself is described in how numbers work in JavaScript, and the type is one of the seven primitives.

What the sum actually is

Print the result with all its digits.

JavaScript
console.log(0.1 + 0.2);
console.log(0.1 + 0.2 === 0.3);
console.log(0.3 - 0.1);
console.log(0.1 * 3);
console.log(0.7 + 0.1);
console.log(0.5 + 0.25);
Text
0.30000000000000004
false
0.19999999999999998
0.30000000000000004
0.7999999999999999
0.75

The last line is exact, and that is the clue. 0.5 and 0.25 are sums of powers of two, so a binary number can hold them with no error. Tenths are not: one tenth in binary is 0.0001100110011... repeating forever, like one third in decimal. The 64-bit format keeps 53 significant bits, so it keeps the nearest value it can, which is slightly more or less than the number you typed.

toFixed() with a long precision shows what is really stored.

JavaScript
console.log((0.1).toFixed(20));
console.log((0.2).toFixed(20));
console.log((0.3).toFixed(20));
console.log((0.1 + 0.2).toFixed(20));
Text
0.10000000000000000555
0.20000000000000001110
0.29999999999999998890
0.30000000000000004441

The stored 0.1 is a little above one tenth and the stored 0.2 a little above one fifth, so their sum lands above the stored 0.3, which is itself a little below three tenths. The sum is the next representable number up from the stored 0.3, and printing the shortest string that identifies it gives 0.30000000000000004.

Comparing with a tolerance

Because results carry tiny errors, compare their difference to a small number and not their values to each other. Number.EPSILON is the gap between 1 and the next larger double, about 2.2 times ten to the minus 16, and it is the right scale for numbers near one.

JavaScript
function nearlyEqual(a, b) {
  const scale = Math.max(1, Math.abs(a), Math.abs(b));
  return Math.abs(a - b) <= Number.EPSILON * scale;
}

console.log(nearlyEqual(0.1 + 0.2, 0.3));
console.log(nearlyEqual(1000.1 + 2000.2, 3000.3));
console.log(nearlyEqual(1, 1.0000001));
console.log(Number.EPSILON);
Text
true
true
false
2.220446049250313e-16

Scaling the tolerance by the magnitude matters. A tolerance of Number.EPSILON alone is far too small for numbers in the thousands, where the gap between neighboring doubles is larger. The function above handles both. For measurements with real-world noise, such as sensor data, pick a tolerance from your domain rather than from the format, because the format's error is the smallest error you will have.

In tests, use the tolerance form built into your runner. Node's assert has no approximate matcher, and Vitest and Jest provide toBeCloseTo, which takes a number of decimal places.

toFixed and rounding

toFixed(n) formats a number with n decimals and returns a string. It rounds the stored binary value, and when the decimal you typed is not exact, the result can be the opposite of what you expect.

JavaScript
console.log((1.005).toFixed(2));
console.log((1.255).toFixed(2));
console.log((2.5).toFixed(0));
console.log(1.005 * 100);
console.log(Math.round(1.005 * 100) / 100);
console.log(typeof (0.1).toFixed(1));
Text
1.00
1.25
3
100.49999999999999
1
string

1.005 is stored as slightly less than itself, so it rounds down to 1.00, where a person doing decimal arithmetic would round up. Multiplying by 100 shows the cause: the product is 100.49999999999999. The result of toFixed() is a string, so arithmetic on it concatenates or coerces, and Number(x.toFixed(2)) is needed when you want a number back. And (2.5).toFixed(0) is "3" because 2.5 is exact, and toFixed rounds exact halves up, a different rule from the banker's rounding some languages use.

For display, prefer Intl.NumberFormat, which rounds with explicit rules and formats for a locale.

JavaScript
const money = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" });

console.log(money.format(1234.5));
console.log(money.format(0.1 + 0.2));
console.log(new Intl.NumberFormat("en-US", { maximumFractionDigits: 2 }).format(1.005));
Text
$1,234.50
$0.30
1.01

Intl.NumberFormat gave 1.01 for 1.005, different from toFixed(). It rounds using the decimal digits of the shortest representation, so it treats 1.005 as typed. Both are defensible, and the point is that you should pick one and test it for your inputs. The post on the Intl API covers formatters in more depth.

Money belongs in integers

The standard fix for currency is to store the smallest unit as an integer: cents, pence, satoshis. Integers up to 9,007,199,254,740,991 are exact in a double, and sums of integers stay exact.

JavaScript
const items = [1999, 549, 1];
const subtotalCents = items.reduce((sum, cents) => sum + cents, 0);
const taxCents = Math.round(subtotalCents * 0.0825);
const totalCents = subtotalCents + taxCents;

console.log(subtotalCents);
console.log(taxCents);
console.log((totalCents / 100).toFixed(2));
Text
2549
210
27.59

Only the tax calculation needs rounding, and it happens once, with Math.round(), on an integer result. The division by 100 happens at the edge, for display. Compare the same total computed in dollars: 19.99 + 5.49 + 0.01 is 25.49 with some digit noise, and the tax multiplied on top adds more.

If your amounts can exceed the safe range, or you need fractions of a cent in a ledger, use BigInt for the integer unit or a decimal library such as decimal.js or big.js. A decimal type is not part of the language today: it exists as a TC39 proposal and has not shipped, so a library is still the answer for decimal arithmetic. See the post on BigInt for the integer route.

When the error does not matter

A chart axis, a progress bar and a game physics step do not care about the seventeenth digit, and adding rounding code to them is noise. The error matters in three places: equality checks on computed values, accumulating many small values in a loop, and anything people read as exact, like money and percentages that must add up to 100.

Accumulation is the quiet one. Summing a hundred thousand values of 0.1 does not give exactly ten thousand, and the drift grows with the count. A compensated sum, such as Kahan's algorithm, or Math.sumPrecise() in runtimes that have ES2026, reduces it, and integers avoid it entirely.

Testing code that does decimal math

A test that asserts a computed decimal equals a literal will fail for reasons unrelated to the logic, and the usual response of rounding both sides in the test hides real errors. A better approach is to test the integer arithmetic exactly and the display formatting separately.

JavaScript
import { test } from "node:test";
import assert from "node:assert/strict";

const totalCents = (items, taxRate) => {
  const subtotal = items.reduce((sum, cents) => sum + cents, 0);
  return subtotal + Math.round(subtotal * taxRate);
};

test("the total is exact in cents", () => {
  assert.equal(totalCents([1999, 549, 1], 0.0825), 2759);
});

test("an empty cart costs nothing", () => {
  assert.equal(totalCents([], 0.0825), 0);
});

Run it with node --test on Node.js 24. The comparison is between integers, so assert.equal is exact and the test never flakes. The display function is tested on its own with a few fixed inputs, so a rounding change shows up in one place.

Where this advice stops

If you work in a domain with its own numeric rules, accounting, tax or scientific computing, follow them over these heuristics. The rule "integers for money" is a default, and a regulated system may require a specific rounding mode at a specific step. Write the mode into the code and a test, so that a reviewer can see which one you chose, and keep the rounding in a single function that every calculation calls, so a change of mode is one edit and not a search.

The format is defined in the specification under the Number type, and MDN's page for Number.EPSILON describes the tolerance used above.

Taggedbeginner
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.