JS floating point calculation bug

Source: Internet
Author: User

Recently when the project encountered a more tangled JS floating point calculation problem.

At that time the interest rate calculation, because the interest rate mostly involves the decimal point, the precision request is also very high.

0.6+0.1+0.1=?

Results appear: 0.7999999999999

Online look up, this is really a flaw (Bug)

In addition, similar situations occur as long as the floating-point calculation is involved in subtraction

First Look at the demo:

Test 0.1~10, plus 0.1+0.1

1$(function () {2             varContent = "";3              for(vari = 0.1; I <= 10; i + = 0.1) {4                 varresult = i + 0.1 + 0.1;5Content = content + result + ' \ t ';6             }7 alert (content);8});

Operation Result:

Workaround:

According to the tofixed method, we modify a Toround method to precisely round the decimal point:

1Number.prototype.toRound =function(d)2         {3             vars= This+"";if(!d) D=0;4             if(S.indexof (".") ==-1) s+= "."; s+=NewArray (d+1). Join ("0");5             if(NewRegExp ("^ (-|\\+)?" ( \\d+ (\\.\\d{0, "+ (d+1) +"})?) \\d*$ "). Test (s))6             {7                 vars= "0" + regexp.$2, pm=regexp.$1, A=regexp.$3.length, b=true;8                 if(a==d+2) {A=s.match (/\d/g);if(parseint (a[a.length-1]) >4)9                 {Ten                      for(varI=a.length-2; i>=0; i--) {A[i] = parseint (A[i]) +1; One                         if(a[i]==10) {a[i]=0; b=i!=1;}Else  Break;} A                 } -S=a.join (""). Replace (NewRegExp ("(\\d+) (\\d{" +d+ "}) \\d$"), "$1.$2"); -}if(b) S=s.substr (1);return(pm+s). Replace (/\.$/, "");}return  This+""; the};

To change the method in the demo, call the Toround method:

var result = (i+0.1+0.1). Toround (2);

Results:

 

 

  

JS floating point calculation bug

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.