Js toFixed of method rewrite to achieve unity of precision

  • 2020-03-30 02:14:39
  • OfStack

Anyone who has ever used the toFix() method in js knows that it has a small BUG.
The decimal carry is a little bit different under IE and FF.
For example (0.005) under ie toFix(2)=0.00. Under FF toFix(2)=0.01.
This can make a difference in the data.
We can achieve uniform precision by rewriting this method.
 
Number.prototype.toFixed = function(s) 
{ 
return (parseInt(this * Math.pow( 10, s ) + 0.5)/ Math.pow( 10, s )).toString(); 
} 

However, there is still a problem with doing this, in all browsers, String("0.050").tofix (2)=0.1
And we can see that you're going to have two decimal places instead of one decimal place. That is to say. This rewrite only has toFixed() which will automatically discard the last 0.
We need to take this method a step further.
 
Number.prototype.toFixed = function(s) 
{ 
changenum=(parseInt(this * Math.pow( 10, s ) + 0.5)/ Math.pow( 10, s )).toString(); 
index=changenum.indexOf("."); 
if(index<0&&s>0){ 
changenum=changenum+"."; 
for(i=0;i<s;i++){ 
changenum=changenum+"0"; 
} 

}else { 
index=changenum.length-index; 
for(i=0;i<(s-index)+1;i++){ 
changenum=changenum+"0"; 
} 

} 

return changenum; 
} 

Related articles: