js中的小数计算精度问题,修正计算精度

js 的精度问题这个网上比较多,进行加减乘除运算也难免,常见的比如:

1)在控制台 输入:1.1+0.3 运算结果是:1.4000000000000001,根本原因也就是二进制和十进制转换的问题,具体源由参考网上相关文章,有一种解决办法:两个数分别剩10的N次方最后再除10的N次方,比如:(1.1*10+0.3*10)/10  ,貌似没有什么问题,但是还是有问题的,只是问题比较隐蔽


2)【容易忽略的精度问题】 比如:

       var  num=35.41;

        num*100结果是什么?3541?

        在调试器和控制台中可以看到,这个值为【3540.9999999999994】,如此看来小数乘10的倍数是存在问题的,

        所以如果页面存在一个需求: 页面小数运算结果为【0】的时候做点什么的话。。。那它就永远也不相等,其结果是一个很接近0的数比如:-6.25e-15;

        所以,把想把小数转整数不是么简单的乘个10的N次方,

       类似的值还有 【20.06】  20.06*100 =?     2005.9999999999998

       解决方法就是,【20.06】拆成,2000 和6 然后分别和100相乘相加再除100  原理是这样,做起来的话,贴代码

// -
// -
minus:function(n,m){
    n=typeof n =="string"?n:this.numToString(n);
    m=typeof m =="string"?m:this.numToString(m);
    var F= n.indexOf(".")!=-1?this.handleNum(n):[n,0,0],
        S= m.indexOf(".")!=-1?this.handleNum(m):[m,0,0],
        l1=F[2],
        l2=S[2],
        L=l1>l2?l1:l2,
        T=Math.pow(10,L);
    return (F[0]*T+F[1]*T/Math.pow(10,l1)-S[0]*T-S[1]*T/Math.pow(10,l2))/T
},
// *
multiply:function(n,m){
    n=typeof n =="string"?n:this.numToString(n);
    m=typeof m =="string"?m:this.numToString(m);
    var F= n.indexOf(".")!=-1?this.handleNum(n):[n,0,0],
        S= m.indexOf(".")!=-1?this.handleNum(m):[m,0,0],
        l1=F[2],
        l2=S[2],
        L=l1>l2?l1:l2,
        T=Math.pow(10,L);
    return ((F[0]*T+F[1]*T/Math.pow(10,l1))*(S[0]*T+S[1]*T/Math.pow(10,l2)))/T/T
},
// /
division:function(n,m){
    n=typeof n =="string"?n:this.numToString(n);
    m=typeof m =="string"?m:this.numToString(m);
    var F= n.indexOf(".")!=-1?this.handleNum(n):[n,0,0],
        S= m.indexOf(".")!=-1?this.handleNum(m):[m,0,0],
        l1=F[2],
        l2=S[2],
        L=l1>l2?l1:l2,
        T=Math.pow(10,L);
    return ((F[0]*T+F[1]*T/Math.pow(10,l1))/(S[0]*T+S[1]*T/Math.pow(10,l2)))
},
numToString:function(tempArray){
    if(Object.prototype.toString.call(tempArray) == "[object Array]"){
        var temp=tempArray.slice();
        for(var i,l=temp.length;i<l;i++){
            temp[i]=typeof temp[i] == "number"?temp[i].toString():temp[i];
        }
        return temp;
    }
    if(typeof tempArray=="number"){
        return tempArray.toString();
    }
    return []
},
plus:function(n,m){
    n=typeof n =="string"?n:this.numToString(n);
    m=typeof m =="string"?m:this.numToString(m);
    var F= n.indexOf(".")!=-1?this.handleNum(n):[n,0,0],
        S= m.indexOf(".")!=-1?this.handleNum(m):[m,0,0],
        l1=F[2],
        l2=S[2],
        L=l1>l2?l1:l2,
        T=Math.pow(10,L);
    return (F[0]*T+F[1]*T/Math.pow(10,l1)+S[0]*T+S[1]*T/Math.pow(10,l2))/T

},
handleNum:function(n){
    n=typeof n !=="string"?n+"":n;
    var temp= n.split(".");
    temp.push(temp[1].length);
    return temp
},


猜你喜欢

转载自blog.csdn.net/sflf36995800/article/details/50612612