JavaScript 比较浮点数的相等

错误的方法

console.log(0.1 + 0.2 == 0.3);

浮点数运算的精度问题导致等式左右的结果并不是严格相等,而是相差了个微小的值。

正确的方法

console.log(Math.abs(0.1 + 0.2 - 0.3) <= Number.EPSILON);

猜你喜欢

转载自www.cnblogs.com/xiaoyucoding/p/11785156.html