zoukankan      html  css  js  c++  java
  • xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

    js double 精度损失 bugs

    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



    ©xgqfrms 2012-2020

    www.cnblogs.com 发布文章使用:只允许注册用户才可以访问!


  • 相关阅读:
    samba中的pdbedit用法
    服务器批量管理工具【转载】
    Linux网卡bounding详解
    Windows下为MySQL做定时备份
    对于新安装的MySQL如何提升MySQL的安全级别
    为Apache动态增加模块
    DSO动态加载PHP模块到Apache服务器
    系统网页打不开,排查故障步骤
    Low overhead memory space management
    pip 升级 Appium-Python-Client
  • 原文地址:https://www.cnblogs.com/xgqfrms/p/13689522.html
Copyright © 2011-2022 走看看