您好,欢迎访问一九零五行业门户网

javascript之对系统的toFixed()方法的修正_javascript技巧

0.009.tofixed(2)本该返回0.01的结果,可它却返回了一个0.00,这是这个方法的一个bug,且这个方法对客户端的js版本要求有点偏高,至少在ie5.0里这个方法用不起来,所以我写了上面的一段修正代码,并且还解决了这个bug的问题。若是想完全使用这个自定义的方法替代那个有bug的系统方法的话,只需要去掉最外层的那个 if 判断就可以了。
//by meizz
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+;
};
}
其它类似信息

推荐信息