WEB开发网
开发学院网页设计JavaScript JavaScript中float的减法与乘法计算错误问题 阅读

JavaScript中float的减法与乘法计算错误问题

 2008-11-05 20:00:01 来源:WEB开发网   
核心提示:if(typeof(Number.PRototype.toFixed)!="function") { Number.prototype.toFixed = function(d) { var s=this+"";if(!d)d=0; if(s.indexOf(&q
if(typeof(Number.PRototype.toFixed)!="function")
{
   Number.prototype.toFixed = function(d)
   {
     var s=this+"";if(!d)d=0;
     if(s.indexOf(".")==-1)s+=".";s+=new Array(d+1).join("0");
     if (new RegExp("^(-|\\+)?(\\d+(\\.\\d{0,"+ (d+1) +"})?)\\d*$").test(s))
     {
       var s="0"+ RegExp.$2, pm=RegExp.$1, a=RegExp.$3.length, b=true;
       if (a==d+2){a=s.match(/\d/g); if (parseInt(a[a.length-1])>4)
       {
         for(var i=a.length-2; i>=0; i--) {a[i] = parseInt(a[i])+1;
         if(a[i]==10){a[i]=0; b=i!=1;} else break;}
       }
       s=a.join("").replace(new RegExp("(\\d+)(\\d{"+d+"})\\d$"),"$1.$2");
     }if(b)s=s.substr(1);return (pm+s).replace(/\.$/, "");} return this+"";
   };
}
0.009.toFixed(2)本该返回0.01的结果,可它却返回了一个0.00,这是这个方法的一个BUG,且这个方法对客户端的JS版本要求有点偏高,至少在IE5.0里这个方法用不起来,所以我写了上面的一段修正代码,并且还解决了这个BUG的问题。若是想完全使用这个自定义的方法替代那个有BUG的系统方法的话,只需要去掉最外层的那个 if 判断就可以了。

Tags:JavaScript float 减法

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接