Summary of JavaScript floating point number and operation Precision Adjustment

Source: Internet
Author: User

Summary of JavaScript floating point number and operation Precision Adjustment

JavaScript has only one numeric type Number, and all numbers in Javascript are represented in IEEE-754 standard format. The precision of floating point numbers is not unique to JavaScript, because some decimals useBinary indicates that the number of digits is infinite..

 
 
  1. Decimal binary
  2. 0.1 0.0001 1001 1001 1001...
  3. 0.2 0.0011 0011 0011 0011...
  4. 0.3 0.0100 1100 1100 1100...
  5. 0.4 0.0110 0110 0110 0110...
  6. 0.5 0.1
  7. 0.6 0.1001 1001 1001 1001...

Therefore, for example, 1.1, the program can not really represent '1. 1', but can only be accurate to a certain extent, which is an unavoidable loss of precision: 1.09999999999999999

The problem in JavaScript is more complicated. Here we only give some test data in Chrome:

 
 
  1. console.log(1.0-0.9 == 0.1)    //false 
  2. console.log(1.0-0.8 == 0.2)    //false 
  3. console.log(1.0-0.7 == 0.3)    //false 
  4. console.log(1.0-0.6 == 0.4)    //true 
  5. console.log(1.0-0.5 == 0.5)    //true 
  6. console.log(1.0-0.4 == 0.6)    //true 
  7. console.log(1.0-0.3 == 0.7)    //true 
  8. console.log(1.0-0.2 == 0.8)    //true 
  9. console.log(1.0-0.1 == 0.9)    //true 

How can we avoid this type of 1.0-0.9! = What happens to 0.1 of non-bug issues? The following provides a more widely used solution. The accuracy of the computing result is reduced before the floating point calculation result is judged, because the accuracy is automatically rounded down:

 
 
  1. (1.0-0.9). toFixed (digits) // toFixed () The accuracy parameter digits must be between 0 and 20
  2. Console. log (parseFloat (1.0-0.9). toFixed (10) === 0.1) // true
  3. Console. log (parseFloat (1.0-0.8). toFixed (10) === 0.2) // true
  4. Console. log (parseFloat (1.0-0.7). toFixed (10) === 0.3) // true
  5. Console. log (parseFloat (11.0-11.8). toFixed (10) ===- 0.8) // true

Write a method:

 
 
  1. // Use the isEqual tool to determine whether the values are equal
  2. Function isEqual (number1, number2, digits ){
  3. Digits = undefined? 10: digits; // The default precision is 10.
  4. Return number1.toFixed (digits) === number2.toFixed (digits );
  5. }
  6. Console. log (isEqual (1.0-0.7, 0.3); // true
  7. // Prototype extension method, prefer the object-oriented Style
  8. Number. prototype. isEqual = function (number, digits ){
  9. Digits = undefined? 10: digits; // The default precision is 10.
  10. Return this. toFixed (digits) === number. toFixed (digits );
  11. }
  12. Console. log (1.0-0.7). isEqual (0.3); // true

Next, let's try the floating point operation,

 
 
  1. console.log(1.79+0.12)  //1.9100000000000001 
  2. console.log(2.01-0.12)   //1.8899999999999997 
  3. console.log(1.01*1.3)    //1.3130000000000002 
  4. console.log(0.69/10)     //0.06899999999999999 

Solution:

 
 
  1. // Addition function, used to obtain accurate addition results
  2. // Note: The addition result of javascript has an error, which is obvious when two floating point numbers are added. This function returns a more accurate addition result.
  3. // Call: accAdd (arg1, arg2)
  4. // Return value: the exact result of adding arg2 to arg1
  5. Function accAdd (arg1, arg2 ){
  6. Var r1, r2, m;
  7. Try {r1 = arg1.toString (). split (".") [1]. length} catch (e) {r1 = 0}
  8. Try {r2 = arg2.toString (). split (".") [1]. length} catch (e) {r2 = 0}
  9. M = Math. pow (10, Math. max (r1, r2 ))
  10. Return (arg1 * m + arg2 * m)/m
  11. }
  12. // Add an add method to the Number type to facilitate calling.
  13. Number. prototype. add = function (arg ){
  14. Return accAdd (arg, this );
  15. }
  16.  
  17. // Subtraction function, used to obtain the exact subtraction result
  18. // Note: The addition result of javascript has an error, which is obvious when two floating point numbers are added. This function returns a more precise subtraction result.
  19. // Call: accSub (arg1, arg2)
  20. // Return value: the exact result of arg1 minus arg2
  21. Function accSub (arg1, arg2 ){
  22. Var r1, r2, m, n;
  23. Try {r1 = arg1.toString (). split (".") [1]. length} catch (e) {r1 = 0}
  24. Try {r2 = arg2.toString (). split (".") [1]. length} catch (e) {r2 = 0}
  25. M = Math. pow (10, Math. max (r1, r2 ));
  26. // Last modify by deeka
  27. // Dynamically control the Precision Length
  28. N = (r1> = r2 )? R1: r2;
  29. Return (arg1 * m-arg2 * m)/m). toFixed (n );
  30. }

 
 
  1. // Division function, used to obtain accurate division results
  2. // Note: the division result of javascript has an error, which is obvious when two floating point numbers are separated. This function returns a more precise division result.
  3. // Call: accDiv (arg1, arg2)
  4. // Return value: the exact result of dividing arg1 by arg2
  5. Function accDiv (arg1, arg2 ){
  6. Var t1 = 0, t2 = 0, r1, r2;
  7. Try {t1 = arg1.toString (). split (".") [1]. length} catch (e ){}
  8. Try {t2 = arg2.toString (). split (".") [1]. length} catch (e ){}
  9. With (Math ){
  10. R1 = Number (arg1.toString (). replace (".",""))
  11. R2 = Number (arg2.toString (). replace (".",""))
  12. Return (r1/r2) * pow (10, t2-t1 );
  13. }
  14. }
  15. // Add a div Method to the Number type to facilitate calling.
  16. Number. prototype. div = function (arg ){
  17. Return accDiv (this, arg );
  18. }
  19.  
  20. // Multiplication function, used to obtain accurate multiplication results
  21. // Note: there is an error in the javascript multiplication result, which is obvious when two floating point numbers are multiplied. This function returns a more accurate multiplication result.
  22. // Call: accMul (arg1, arg2)
  23. // Return value: the exact result of multiplying arg1 by arg2
  24. Function accMul (arg1, arg2 ){
  25. Var m = 0, s1 = arg1.toString (), s2 = arg2.toString ();
  26. Try {m + = s1.split (".") [1]. length} catch (e ){}
  27. Try {m + = s2.split (".") [1]. length} catch (e ){}
  28. Return Number (s1.replace (".", "") * Number (s2.replace (".", "")/Math. pow (10, m)
  29. }
  30. // Add a mul Method to the Number type to facilitate calling.
  31. Number. prototype. mul = function (arg ){
  32. Return accMul (arg, this );
  33. }
  34. <Br> // verify the following:
  35. Console. log (accAdd (1.79, 0.12); // 1.91
  36. Console. log (accSub (2.01, 0.12); // 1.89
  37. Console. log (accDiv (0.69, 10); // 0.069 <br> console. log (accMul (1.01, 1.3); // 1.313

After the transformation, You can happily perform the floating point addition, subtraction, multiplication, division operation ~

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.