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

// 保留两位精度 ?

 

解决方案

  1. 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 大数相加, ??? 位运算

 

  1. 小数转整数
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

ES6 ...rest

const arr = [
     2.48, 13.77,  8.64,
    20.17,  8.94,  8.07,
    12.05,  5.71, 17.54,
     2.63
  ];
// (10) [2.48, 13.77, 8.64, 20.17, 8.94, 8.07, 12.05, 5.71, 17.54, 2.63]

const [min, ...rest1] = arr.sort((a, b) => a - b > 0 ? 1 : -1);
// (10) [2.48, 2.63, 5.71, 8.07, 8.64, 8.94, 12.05, 13.77, 17.54, 20.17]

min;
// 2.48

const [max, ...rest2] = arr.sort((a, b) => a - b > 0 ? -1 : 1);
// (10) [20.17, 17.54, 13.77, 12.05, 8.94, 8.64, 8.07, 5.71, 2.63, 2.48]

max;
// 20.17

 

posted @ 2020-09-25 22:54  桥南小院  阅读(179)  评论(0编辑  收藏  举报