Why (0.1 + 0.2) + 0.3 is different from 0.1 + (0.2 + 0.3)?

Asked

Viewed 286 times

4

Javascript (0.1 + 0.2) + 0.3 results in 0.6000000000000001. Already, 0.1 + (0.2 + 0.3) results in 0.6.

Why?

In the snippet, you can see that this "inconsistency" does not happen when we add other values.

console.log((0.1 + 0.2) + 0.3);
console.log(0.1 + (0.2 + 0.3));

console.log('-----');

console.log((0.4 + 0.5) + 0.6);
console.log(0.4 + (0.5 + 0.6));

  • 1

    Hi jbueno! I think this question is duplicated of this other. If you do not agree says. Basically there is a problem in the calculation since that 0.1 + 0.2 gives 0.30000000000000004 and 0.2 + 0.3 gives 0.5

  • 2

    show of Zueira against Javascript today :D

  • 2

    It’s duplicated yes, @Sergio. I didn’t know how to use the right words to search. I just don’t understand why the negatives =D

  • Great! The negative vote may be because it is a +/- common problem. If that’s not the reason why it won’t be.

  • Hehehe, yes. It happens. Now that I noticed it was just a negative, I had made a mistake.

  • Now I understand why that question had revisits today... = D

  • 1

    In any case, the underlying cause in this case is a little different. It is not the representation that is misleading, but the operation + which introduces the error in 0.1 + 0.2 resulting in 0.30000000000000004 and then when adding 0.3 the error is not only propagated, it is also amplified, again the fault of the operator +.

  • When changing the order of operations this error is not entered. When 0.2 + 0.3 that exactly gives 0.5 and then when adding 0.1 the representation becomes exactly that of 0.6... which is no luck, since 0.5 is a round binary number.

  • 1

    To see how the numbers are represented in binary form use this site: IEEE-754 Analysis... it’s a bit of a hassle to take the binary representation and operate bit by bit to see what’s going on, but it already helps a lot.

Show 4 more comments
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.