Home  >  Article  >  Web Front-end  >  Rewriting the js toFixed() method to achieve unification of precision_javascript skills

Rewriting the js toFixed() method to achieve unification of precision_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:56:442890browse

Anyone who has used the toFix() method in js should know that there is a small BUG in this method.
The carry of decimals is a little different under IE and FF.
For example (0.005) under IE toFix(2)=0.00. Under FF toFix(2)=0.01.
This will cause data differences.
We can achieve unification of precision by overriding this method.

Copy code The code is as follows:

Number.prototype.toFixed = function(s)
{
return (parseInt(this * Math.pow( 10, s ) 0.5)/ Math.pow( 10, s )).toString();
}

But There is still a problem with this. Under all browsers, String("0.050").toFix(2)=0.1
We can see that you originally wanted to keep two decimal places but it became one. That is to say. The only toFixed() in this override will automatically discard the last 0.
We need to further process this method.
Copy code The code is as follows:

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;ichangenum=changenum "0";
}

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

}

return changenum;
}
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn