Solution of floating point number:- JavaScript


  • You can solve this problem by using parseFloat(number.toPrecision(12));.
  • It will depend on what kind of calculations you are doing.

  • Code:-

    1. <!DOCTYPE html> 
    2. <html> 
    3.  
    4. <head> 
    5.  <meta name="viewport" content="width=device-width, initial-scale=1"> 
    6. </head> 
    7.  
    8. <body> 
    9.  
    10.  <h1>Solution of Floating point problem</h1> 
    11.  
    12.  <input type="button" value="check Answer" onclick="chk_ans();"> 
    13.  
    14.  <script> 
    15.   /* 
    16.       What can I do to avoid this problem? 
    17.  
    18.       That depends on what kind of calculations you’re doing. 
    19.  
    20.       If you really need your results to add up exactly, especially when you work with money: use a special decimal datatype. 
    21.       If you just don’t want to see all those extra decimal places: simply format your result rounded to a fixed number of decimal places when displaying it. 
    22.       If you have no decimal datatype available, an alternative is to work with integers, e.g. do money calculations entirely in cents. But this is more work and has some drawbacks. 
    23.  
    24.       Solution 
    25.            The following solution will help you to solve your problem.  
    26.       */ 
    27.   function chk_ans() 
    28.   { 
    29.    alert(((0.1 * 10) + (0.2 * 10)) / 10); 
    30.   } 
    31.  </script> 
    32.  
    33. </body> 
    34.  
    35. </html>
    Solution of floating point number:- JavaScript Solution of floating point number:- JavaScript Reviewed by Network security on November 05, 2019 Rating: 5

    No comments:

    Useful Information

    Powered by Blogger.