Rewrite js toFixed () method to unify precision

Source: Internet
Author: User

Anyone who has used the toFix () method in js should know that this method has a small BUG.
In IE and FF, the decimal places are a little different.
For example, (0.005) in ie, toFix (2) = 0.00. In FF, toFix (2) = 0.01.
This will lead to data differences.
We can rewrite this method to unify precision.
Copy codeThe 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 in doing so, in all browsers, String ("0.050"). toFix (2) = 0.1
We can see that you originally wanted to keep two decimal places but changed to one. That is to say. Only the toFixed () of this rewrite will automatically discard the last 0.
We need to further process this method.
Copy codeThe 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; 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 Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.