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.1
The 0.2
binary 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
).
ES2015
This 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