minjs1cn / weekly-learning

每周学习分享打卡
0 stars 0 forks source link

21 -【经典面试】为什么 0.1 + 0.2 ≠ 0.3,如何解决? #21

Open OceanApart opened 3 years ago

wucuiping commented 3 years ago

https://juejin.cn/post/6844903680362151950

OceanApart commented 3 years ago

1

1. 最小精度

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);
}

2. 分数表示

将小数转为分数存储、计算。那么就变成如何转化

3. BigNumbers 更高精度

64位,精度更高,但是计算更慢,而且无法处理无限循环数 0.33333333....

4. 四舍五入保留精度

MathUtils = {
  roundToPrecision: function(subject, precision) {
    return +((+subject).toFixed(precision));
  }
};

console.log(MathUtils.roundToPrecision(-0.1 + -0.2, 1)) // 0.9;
FE92star commented 3 years ago

https://segmentfault.com/a/1190000012175422