JavaScript-Optimized subtraction (solves JS floating-point calculation bug)

Source: Internet
Author: User
Tags mul

Description

As we all know, JS calculates the floating-point number, the result may be inaccurate. For example: (Results of the calculations in Chrome)
2.2 + 2.1 = 4.300000000000001
2.2-1.9 = 0.30000000000000027
2.2 * 2.2 = 4.840000000000001
2.1/0.3 = 7.000000000000001

Online code Spread (bug)

The optimized code is circulated online as follows (problematic code, do not use)

 function add(A, B) {    varC, D, E;Try{c = a.tostring (). Split (".")[1].length; }Catch(f) {c =0; }Try{d = b.tostring (). Split (".")[1].length; }Catch(f) {d =0; }returnE =Math. POW (Ten,Math. Max (c, D)), (A * e + b * e)/E;} function Sub(A, B) {    varC, D, E;Try{c = a.tostring (). Split (".")[1].length; }Catch(f) {c =0; }Try{d = b.tostring (). Split (".")[1].length; }Catch(f) {d =0; }returnE =Math. POW (Ten,Math. Max (c, D)), (A * e-b * e)/E;} function mul(A, B) {    varc =0, d = a.tostring (), E = b.tostring ();Try{c + = D.split (".")[1].length; }Catch(f) {}Try{c + = E.split (".")[1].length; }Catch(f) {}return  Number(D.replace (".","")) * Number(E.replace (".","")) /Math. POW (Ten, c);} function div(A, B) {    varC, d, E =0, F =0;Try{e = A.tostring (). Split (".")[1].length; }Catch(g) {}Try{f = b.tostring (). Split (".")[1].length; }Catch(g) {}returnc = Number(A.tostring (). Replace (".","")), d = Number(B.tostring (). Replace (".","")), C/D *Math. POW (Ten, F-E);}

The principle is to convert floating-point numbers to integers.

Problem Code Test

But the above optimization method really solves the problem, we can simply do the test.
The test code is as follows: (addition in test operation)

 function test(){    varA = (Math. Random () * -). ToFixed (2) -0;varB = (Math. Random () * +). ToFixed (2) -0;varresult = Add (a, b);if(Result +"'). length >Ten) {Console.error (' Summand: '+a,' addend: '+b,' Result: '+result);return; } setTimeout ( function() {Test (); },Ten);} Test ();
Problem code Test results

The browser console quickly prints the results, explaining that the additive operation code being tested has an inaccurate operation.
Test Run Results:

Problem code Error Reason

Since there is a problem with the above code, the point where the error occurs, we will debug the code with the wrong number.
by Addend: 19.36 addend: 601.19 results: 620.5500000000001
The debugging process and results are as follows:

We found that the multiplication calculation was wrong.

Correction method

There are some versions of the Web that you will find to add tofixed when the results are finally returned, which is a workaround.
And since it's a multiplication error, why don't we replace the multiplication with the optimized one. For example, the modified additions are as follows:

function  add   (A, b)  { var  C, D, E; try  {c = a.tostring (). Split ()    [1 ].length;    } catch  (f) {c = 0 ; } try  {d = b.tostring (). Split ()    [1 ].length;    } catch  (f) {d = 0 ; } return  e = math . Pow ( 10 , math . Max (c, D)), (Mul (A, E) + mul (b, E))/E;} 

Then use the above method to test, waiting for "one day", the console also did not print. This time, it really solves the problem.

Final version (correct version)
 function add(A, B) {    varC, D, E;Try{c = a.tostring (). Split (".")[1].length; }Catch(f) {c =0; }Try{d = b.tostring (). Split (".")[1].length; }Catch(f) {d =0; }returnE =Math. POW (Ten,Math. Max (c, D)), (Mul (A, E) + mul (b, E))/E;} function Sub(A, B) {    varC, D, E;Try{c = a.tostring (). Split (".")[1].length; }Catch(f) {c =0; }Try{d = b.tostring (). Split (".")[1].length; }Catch(f) {d =0; }returnE =Math. POW (Ten,Math. Max (c, D)), (Mul (A, E)-Mul (b, E))/E; function mul(A, B) {    varc =0, d = a.tostring (), E = b.tostring ();Try{c + = D.split (".")[1].length; }Catch(f) {}Try{c + = E.split (".")[1].length; }Catch(f) {}return  Number(D.replace (".","")) * Number(E.replace (".","")) /Math. POW (Ten, c);} function div(A, B) {    varC, d, E =0, F =0;Try{e = A.tostring (). Split (".")[1].length; }Catch(g) {}Try{f = b.tostring (). Split (".")[1].length; }Catch(g) {}returnc = Number(A.tostring (). Replace (".","")), d = Number(B.tostring (). Replace (".",""), Mul (C/D,Math. POW (Ten, f-e));}

JavaScript-Optimized subtraction (solves JS floating-point calculation bug)

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: 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.