Correction of the tofixed () method in the system using JavaScript

Source: Internet
Author: User

0.009.tofixed (2) should have returned the result of 0.01, But it returns a 0.00 error. This is a bug in this method, and this method has a high requirement on the JS version of the client, at least this method cannot be used in ie5.0, so I wrote the above correction. Code And solved the bug. If you want to completely use this custom method to replace the system method with bugs, you only need to remove the if judgment on the outermost layer.

// 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 =. join (""). replace (New Regexp ("(\ D +) (\ D {" + D + "}) \ D $"), "$1. $2 ");

} If (B) S = S. substr (1 );
Return (PM + S). Replace (/\. $ /,"");

} Return this + "";

};

}

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: info-contact@alibabacloud.com 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.