The error solution for the float value calculation by JavaScript

Source: Internet
Author: User

<Script language ="JavaScript">

Alert (87593.21-3.12 );

</SCRIPT>

Correctly displayed: 87590.09
But the result is: 87590.09000000001.

Tofixed can be used for processing, such:

<Script language ="JavaScript">

Alert (87593.21-3.12). tofixed (2 ));

</SCRIPT>

---------------------------------

Tofixed method problems:

<Script language ="JavaScript">

Alert (0.009.tofixed (2 ));

</SCRIPT>

The calculation result is 0.00, But 0.01 is required.

Solution:

Number. Prototype. tofixed =Function(D)

{

VaRS =This+"";If(! D) d = 0;

If(S. indexof (".") =-1) S + ="."; S + =NewArray (D + 1). Join ("0");

If(NewRegexp ("^ (-| \\+ )? (\ D + (\. \ D {0 ,"+ (D + 1) +"})?) \ D * $"). Test (s ))

{

VaRS ="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(VaRI = 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 = A. Join (""). Replace (NewRegexp ("(\ 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.