zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    Object.defineProperty实现数据绑定
    trigger回调方法的实现
    window.print()打印页面指定内容(使用iframe保证原页面不失效)
    Visual Studio Code 快捷键大全(Windows)
    个人博客-逐梦博客,宋
    Vue.js项目在apache服务器部署后,刷新404的问题
    阿里云ECS服务器Ubuntu配置MySQL远程访问
    最全面的css布局
    js中数组常用方法总结
    PHP环境搭建
  • 原文地址:https://www.cnblogs.com/wheatCatcher/p/13733028.html
Copyright © 2011-2022 走看看