js double 精度损失 bugs All In One
js double 精度损失 bugs All In One
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
最简单的方法实现微信红包的随机算法
https://www.cnblogs.com/xgqfrms/p/13688375.html
©xgqfrms 2012-2020
www.cnblogs.com 发布文章使用:只允许注册用户才可以访问!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/13689522.html
未经授权禁止转载,违者必究!