TryBugHunt

0.1 + 0.2 is 0.30000000000000004

0.1 + 0.2 is 0.30000000000000004 in JavaScript means javaScript numbers are binary floating point, and 0.1 cannot be stored exactly. The tiny error shows up when you add, compare or print.

JavaScriptPattern: Type errors

How do I fix 0.1 + 0.2 is 0.30000000000000004?

In JavaScript, 0.1 + 0.2 is 0.30000000000000004 because every number is a binary floating point value, and 0.1 cannot be stored exactly. It is not a bug. Format numbers for display with toFixed(2), compare with a tolerance using Math.abs(a - b) < Number.EPSILON, and store money as whole cents.

  1. 1. Remove exact float equalityReplace a + b === c with Math.abs(a + b - c) < Number.EPSILON, or a tolerance that suits your data.
  2. 2. Format for displayShow values with toFixed(2) or Intl.NumberFormat instead of printing the raw number.
  3. 3. Money in centsKeep prices as integers like 1999 and divide by 100 only when you display them.

What does 0.1 + 0.2 is 0.30000000000000004 mean?

Every number in JavaScript is a 64-bit float. Just as 1/3 has no exact decimal form, 0.1 has no exact binary form, so it is stored as the nearest value. Adding two approximations gives 0.30000000000000004, and 0.1 + 0.2 === 0.3 is false. This is not a JavaScript bug: Python, Java and C behave the same way.

Why does 0.1 + 0.2 is 0.30000000000000004 happen?

1. Comparing floats with ===

Exact equality fails by the smallest possible amount.

Breaks

if (0.1 + 0.2 === 0.3) { ... }

Works

if (Math.abs(0.1 + 0.2 - 0.3) < Number.EPSILON) { ... }

2. Money stored as decimal amounts

Rounding errors accumulate across a cart or ledger.

Breaks

const total = 0.1 + 0.2;   // 0.30000000000000004

Works

const totalCents = 10 + 20;   // work in whole cents
const total = totalCents / 100;

3. Printing a raw float

Display needs formatting, not a different number.

Breaks

label.textContent = price * qty;

Works

label.textContent = (price * qty).toFixed(2);

How to find it in your own code

Decide what you need: for display, format with toFixed(2) or Intl.NumberFormat; for comparisons, allow a tolerance; for money, keep whole cents as integers and divide only for display.

Try it: fix this bug

medium

addPrices(0.1, 0.2) returns 0.30000000000000004.

function addPrices(a, b) {
    return a + b;
}
Open with hintsRuns in your browser. No account needed.

Still not sure why yours breaks?

Paste it into the visualizer and watch it run line by line, with every variable at every step. Free, and it runs in your browser.

Related error guides

View all type errors →