Open OceanApart opened 3 years ago
Number.EPSILON,最接近 1 的浮点数与 1 的差值;
const result = Math.abs(0.2 - 0.3 + 0.1);
console.log(result);
// expected output: 2.7755575615628914e-17
console.log(result < Number.EPSILON);
// expected output: true
/* Polyfill */
if (Number.EPSILON === undefined) {
Number.EPSILON = Math.pow(2, -52);
}
将小数转为分数存储、计算。那么就变成如何转化。
64位,精度更高,但是计算更慢,而且无法处理无限循环数 0.33333333....
MathUtils = {
roundToPrecision: function(subject, precision) {
return +((+subject).toFixed(precision));
}
};
console.log(MathUtils.roundToPrecision(-0.1 + -0.2, 1)) // 0.9;
https://juejin.cn/post/6844903680362151950