js double 精度损失 bugs
bug图示:
const arr = [ 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01 ]; // [0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01] arr.reduce((acc, i) => acc += i); // 0.09999999999999999
arr = [ 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01 ] (10) [0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01] arr.reduce((acc, i) => acc += i); 0.09999999999999999 sum = 0; 0 sum += 0.01; 0.01 sum += 0.01; 0.02 sum += 0.01; 0.03 sum += 0.01; 0.04 sum += 0.01; 0.05 sum += 0.01; 0.060000000000000005 sum += 0.01; 0.07 sum += 0.01; 0.08 sum += 0.01; 0.09 sum += 0.01; 0.09999999999999999 // 保留两位精度 ?
解决方案
- string 大数相加 / 大数相乘
arr = [ 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01 ]; (10) [0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01] arr.reduce((acc, i) => acc += Number.parseFloat(i).toFixed(2)); "0.010.010.010.010.010.010.010.010.010.01" arr.reduce((acc, i) => acc += parseFloat(i.toFixed(2))); 0.09999999999999999 arr.reduce((acc, i) => acc += i.toFixed(2)); "0.010.010.010.010.010.010.010.010.010.01" arr.map(i => i.toFixed(2)); (10) ["0.01", "0.01", "0.01", "0.01", "0.01", "0.01", "0.01", "0.01", "0.01", "0.01"] // string 大数相加, ??? 位运算
- 小数转整数
arr = [ 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01 ]; (10) [0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01] arr.map(i => i * 100).reduce((acc, i) => acc += i) / 100; 0.1
红包算法
refs
最简单的方法实现微信红包的随机算法
ES6 ...rest