JavaScript 比较浮点数的相等

错误的方法

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

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

正确的方法

console.log(Math.abs(0.1 + 0.2 - 0.3) <= Number.EPSILON);
posted @ 2019-11-03 08:59  月半流云  阅读(1257)  评论(0编辑  收藏  举报