This is the 8th day of my participation in the August Text Challenge.More challenges in August
The answer is:
0.1 + 0.2 does not equal 0.3!
Google Chrome runs as follows:
When you look at the browser console, the result is an odd 0.30000000000000004 instead of 0.3
That’s because our computers have a basic principle when it comes to storing data:
With limited storage space, to store binary data.
There are two key points to the above statement:
- Limited storage space
- Binary data
Keep them in mind.
Here we go:
That is, whether 0.1 or 0.2, our computer first converts it to binary 0.1 and 0.2
However, when decimal 0.1 is converted to binary, the result is an infinite repeating decimal: 0.00011… The same is true when 0.2 in decimal is converted to binary
Here’s a key takeaway: binary cannot represent 0.1 and 0.2 “in finite number of bits.
In conclusion:
The computer uses a finite amount of space to store binary 0.1 and 0.2 (but this is bound to lose precision)
So the computer stores approximations of 0.1 and 0.2.
That’s it. When you add two approximations, you get an approximation of 0.3 with maximum probability.
So 0.1 + 0.2! == 0.3.
Also, this isn’t just a JavaScript problem, 0.30000000000000004.com/ lists the results for various languages with 0.1 + 0.2…
Floating point arithmetic with JS is not recommended
Due to the aforementioned loss of precision, it is not recommended to use JS for floating-point calculations, especially for “money” scenarios.
Before performing floating-point operations, we also try to determine whether the absolute value of the difference between two floating-point numbers exceeds the error precision:
function fn(a, b) {
return Math.abs(a - b) < Number.EPSILON
}
fn(0.1 + 0.2.0.3)
Copy the code
Introducing decimal arithmetic
TC39 Decimal proposal
The default number operation in JS is actually an implicit conversion to binary operation, so now there is a proposal for decimal operation, that is, 0.1 + 0.2! == 0.3 will no longer exist in JS.