A, 0.1 + 0.2! == 0.3 why?

We all know that floating-point meters are imprecise, and the 0.1 + 0.2 return actually looks like this:

0.1 + 0.2 = 0.30000000000000004


So how do we figure this out? We all know that everything in a computer is binary, if you have unlimited precision.

0.1 to binary is 0.0001100110011001100110011 infinite loop)

0.2 converted to binary is 0.0011001100110011(0011 infinite loop)

Since both 0.1 and 0.2 are infinite repeating decimals, how is 0.1 + 0.2 = 0.30000000000000004 calculated?

In JS, the Number type, binary decimals have only 52 significant digits, from 0 to 51 (including boundaries)

Js is defined above, so we output it in the console

0.1. The toString (‘ 2 ‘)

0.001100110011001100110011001100110011001100110011001101

0.2. The toString (‘ 2 ‘)

0.0001100110011001100110011001100110011001100110011001101

So here’s the formula

0.001100110011001100110011001100110011001100110011001101

+

0.0001100110011001100110011001100110011001100110011001101

=

0.0100110011001100110011001100110011001100110011001100


while

It is 0.300000000000000004 0.0100110011001100110011001100110011001100110011001100 (17 decimal number) in binary form.


That’s why 0.1 + 0.2 = 0.30000000000000004.


How to make 0.1+0.2 === 0.3

So how can we solve the problem that 0.1+0.2 equals 0.3? The best way to do this is to set a range of error, usually called “machine precision”, which for Javascript is usually 2^-52. In ES6, we already have a property called number.epsilon, which is exactly 2^-52. It’s a very, very small value, which the computer did for us at the bottom, and it’s infinitely close to zero, but not equal to zero. (0.1+0.2)-0.3 is less than Number.EPSILON. Within the error range, 0.1+0.2===0.3 is true.

function numberepsilon(arg1, arg2){
        return Math.abs(arg1 – arg2) < Number.EPSILON;
}
The console. The log (numberepsilon (0.1 + 0.2, 0.3));

The output of true

This property is supported in FireFox and Chrome, but not in IE (IE10 and below are not compatible), so we need to address the incompatibility issue in IE.

Number.epsilon =(function(){// Resolve compatibility issues
return Number.EPSILON? Number.EPSILON:Math.pow(2,-52);
}) ();


Solution: We use a self-calling function that evaluates and returns a result as soon as the JS file is loaded into memory. This code is more efficient and beautiful.


Conclusion: to be a hard-working, diligent, proactive front-end engineer