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


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.{GetProperty(Content)}, 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$"),"{GetProperty(Content)}.$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 判断就可以了


« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3