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?
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.
- 1Why is the string immutable in c#
- 6how to check if object is empty or not.
- 1nmap: what does “80/tcp filtered http” mean
- 2how to check is array symmetrical or not?
- 2What does Git-blame do?
- 2how to check a number is prime or not. using js
- 1How to automatically set the margins of the child element so they become equal.
- 2line-height property not work with hyperlinks?
- 1How to check does a specific branch contains a given commit in Git
- 6Do you use CSS ::placeholder Pseudo Element? Why?