Home > Article > Web Front-end > JavaScript correction to the system’s toFixed() method_javascript skills
0.009.toFixed(2) should have returned a result of 0.01, but it returned a 0.00. This is a BUG of this method, and this method requires a bit high JS version of the client, at least in IE5.0. It didn't work, so I wrote the above correction code and solved the BUG problem. If you want to completely use this custom method to replace the buggy system method, you only need to remove the outermost if judgment.
//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; -1])>4)
{
for(var i=a.length-2;i>=0;i--){
a[i]=parseInt(a[ 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 "";
};
}