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));
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
gives0.30000000000000004
and0.2 + 0.3
gives0.5
– Sergio
show of Zueira against Javascript today :D
– Wallace Maxters
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
– Jéf Bueno
Great! The negative vote may be because it is a +/- common problem. If that’s not the reason why it won’t be.
– Sergio
Hehehe, yes. It happens. Now that I noticed it was just a negative, I had made a mistake.
– Jéf Bueno
Now I understand why that question had revisits today... = D
– Miguel Angelo
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 in0.1 + 0.2
resulting in0.30000000000000004
and then when adding0.3
the error is not only propagated, it is also amplified, again the fault of the operator+
.– Miguel Angelo
When changing the order of operations this error is not entered. When
0.2 + 0.3
that exactly gives0.5
and then when adding0.1
the representation becomes exactly that of0.6
... which is no luck, since0.5
is a round binary number.– Miguel Angelo
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.
– Miguel Angelo