Why does 0.8 + 0.4 not equal 1.2

Ask a question+

Been coding in javascript and came across a weird bug. I got passed values of 0.8 and 0.4 and when I added them together I got 1.2000000000000002

You can replicate it by doing a console.log(0.8+0.4)

Anyone know why my numbers are not adding up correctly, and also how to get them to going forward?

Lainrawr 305
add comment

1 Answer

0.1 + 0.2  // 0.30000000000000004

A number is stored in memory in its binary form, a sequence of bits – ones and zeroes. But fractions like 0.1, 0.2 that look simple in the decimal numeric system are actually unending fractions in their binary form.

In other words, what is 0.1? It is one divided by ten 1/10, one-tenth. In decimal numeral system such numbers are easily representable. Compare it to one-third: 1/3. It becomes an endless fraction 0.33333(3).

So, division by powers 10 is guaranteed to work well in the decimal system, but division by 3 is not. For the same reason, in the binary numeral system, the division by powers of 2 is guaranteed to work, but 1/10 becomes an endless binary fraction.

There’s just no way to store exactly 0.1 or exactly 0.2 using the binary system, just like there is no way to store one-third as a decimal fraction.

The numeric format IEEE-754 solves this by rounding to the nearest possible number. These rounding rules normally don’t allow us to see that “tiny precision loss”, but it exists.

We can see this in action:

  0.1.toFixed(20)  // 0.10000000000000000555

And when we sum two numbers, their “precision losses” add up.

That’s why 0.1 + 0.2 is not exactly 0.3.

Thanks for the answer. Accepted it.

add comment

Your Answer