0.1 + 0.2 !== 0.3 // true

 

var a=0.1;
var b=0.2;
var c=0.3;
console.log(a+b!==c);//true

 All programming languages ​​implemented using IEEE-754 numbers have this problem.

 

0.1The 0.2binary floating-point representation of the sum is not exact, so it does not equal when added 0.3. The result of this addition is close0.30000000000000004 .

So what if you must want to compare the added result with the expected number? Tolerance comparison, that is, to allow a certain error, the error value is generally 2^-52 ( 2.220446049250313e-16).

 

ES2015This value is normalized and can be obtained byNumber.EPSILON

var a = 0.1;
var b = 0.2;
var c = 0.3;
var equal = (Math.abs(a  + b - c) < Number.EPSILON);
console.log(equal); //true

 Use this issue to verify the equality of floating point numbers

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326757676&siteId=291194637