Correction of the toFixed () method in javascript _ javascript skills
Source: Internet
Author: User
Javascript-correction to the system's toFixed () method 0.009.toFixed (2) should have returned the result of 0.01, But it returns a 0.00, which is a BUG in this method, in addition, 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, this BUG is also solved. 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 (/\. $ /,"");
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.