• js计算小数精度问题


    js进行部分小数运算时,会出现精度问题。

     解决思路是,把小数同时扩大为10的x幂,返回计算完毕后,再缩小为10的x幂。

    在Math方法上添加加减乘除方法。

    let extentFns = ['add', 'sub', 'mul', 'div'];
    //运算函数
    function ufunc(type, arg){
      var decimalDigits = []; //要计算的小数位数数组
      //获取小数点的位数
      for(let index in arg){
        let digit = 0;
        try {  
          digit = arg[index].toString().split(".")[1].length;
        }catch (e) { 
          digit = 0; 
        }
        decimalDigits.push(digit);
      }
      //找到最大的位数
      decimalDigits.sort( (a, b)=> a - b );
      let maxDigit = decimalDigits[decimalDigits.length - 1];
      let m = Math.pow(10, maxDigit);//小数转换成整数需要扩大的倍数
      let result = 0;
      switch(type){
        case 'add':
          for(let index in arg){
            result += arg[index] * m;
          }
          return result / m;
          break;
        case 'sub':
          for(let index in arg){
            if(index == 0){
              result = arg[index] * m - result;
            }else{
              result -= arg[index] * m
            }       
          }
          return result / m;
          break;
        case 'mul':
          result = 1;
          for(let index in arg){
            if(index == 0){
              result = arg[index] * m * result;
            }else{
              result *= arg[index] * m
            }       
          }
          return result / m;
          break;
        case 'div':
          result = 1;
          for(let index in arg){
            if(index == 0){
              result = arg[index] * m / result;
            }else{
              result /= arg[index] * m
            }       
          }
          return result / m;
          break;
        default:
          break;
          
      }
    }
    Math.ufunc = ufunc;
    
    //挂载到Math上
    // Math.add1 = add1;
    for(let i = 0; i < extentFns.length; i++){
      Math[extentFns[i]] = function(){
        return this.ufunc(extentFns[i], arguments);
      };
    }
    //参数可以连续传递 Math.add(0.1, 0.2, 0.3, ....);
    console.log( Math.add(0.1,0.2)); //0.3
    console.log( Math.sub(0.12,0.2));
    console.log( Math.mul(0.2,0.4));
    console.log( Math.div(0.2,0.04));

    想使用时引入这个js文件即可在Math方法上找到这几个函数了。

    参考:https://blog.csdn.net/caiminiu/article/details/87071668

  • 相关阅读:
    Dev:LookUpEdit的用法
    Excel:写入Excel单纯写入
    浅拷贝与深拷贝
    自行车的种类
    简单的话
    Excel:导入导出原文02
    VS2010中出现无法嵌入互操作类型
    U盘有时候不显示(win7 64位)
    Knockout学习之Single Page Application
    CSS点滴整理
  • 原文地址:https://www.cnblogs.com/taohuaya/p/12551615.html
Copyright © 2020-2023  润新知