• JS浮点类型运算精度丢失问题解决办法


    //加法  
    Number.prototype.add = function(arg){  
        var r1,r2,m;  
        try{r1=this.toString().split(".")[1].length}catch(e){r1=0}  
        try{r2=arg.toString().split(".")[1].length}catch(e){r2=0}  
        m=Math.pow(10,Math.max(r1,r2))  
        return (this*m+arg*m)/m  
    }  
     
    //减法  
    Number.prototype.sub = function (arg){  
        return this.add(-arg);  
    }  
     
    //乘法  
    Number.prototype.mul = function (arg)  
    {  
        var m=0,s1=this.toString(),s2=arg.toString();  
        try{m+=s1.split(".")[1].length}catch(e){}  
        try{m+=s2.split(".")[1].length}catch(e){}  
        return Number(s1.replace(".",""))*Number(s2.replace(".",""))/Math.pow(10,m)  
    }  
     
    //除法  
    Number.prototype.div = function (arg){  
        var t1=0,t2=0,r1,r2;  
        try{t1=this.toString().split(".")[1].length}catch(e){}  
        try{t2=arg.toString().split(".")[1].length}catch(e){}  
        with(Math){  
            r1=Number(this.toString().replace(".",""))  
            r2=Number(arg.toString().replace(".",""))  
            return (r1/r2)*pow(10,t2-t1);  
        }  
    }

        alert(0.1+0.2)                  //  0.30000000000000004      

    alert(Number(0.1).add(0.2));         //  0.3

    原文地址:

    http://zm6.sm-img5.com/?src=http%3A%2F%2Fblog.csdn.net%2Fqq282030166%2Farticle%2Fdetails%2F8364343&uid=786557245b09f79404ff7abb851dd3a0&hid=a5df8b9ce3035b5c528b414288832958&pos=4&cid=9&time=1440477098910&from=click&restype=1&pagetype=0040000002000408&bu=web&query=js%E7%B2%BE%E5%BA%A6%E4%B8%A2%E5%A4%B1&uc_param_str=dnntnwvepffrgibijbprsvpi

     
  • 相关阅读:
    bootstrap
    jQuery快速入门
    前端jQuery
    前端BOM和DOM
    前端js
    前端css
    前端知识之HTML内容
    线程池
    线程
    LightOJ
  • 原文地址:https://www.cnblogs.com/cbliu/p/6929494.html
Copyright © 2020-2023  润新知