Problems of floating point number:- JavaScript


When you doing airthmetic operation some times you will get unexpected answer like 0.1 + 0.2=0.30000000000000004 this is floating point error. For more details Click Here.

Code:-


  • <!DOCTYPE html> 

    1. <html> 
    2.  
    3. <head> 
    4.  <meta name="viewport" content="width=device-width, initial-scale=1"> 
    5. </head> 
    6.  
    7. <body> 
    8.  
    9.  <h1>Floating point problem</h1> 
    10.  
    11.  <input type="button" value="check 0.1+0.2" onclick="chk_ans();"> 
    12.  <script> 
    13.   /* 
    14.       Binary floating point math is like this. In most programming languages, it is based on the IEEE 754 standard. JavaScript uses 64-bit floating point representation, which is the same as Java's double. The crux of the problem is that numbers are represented in this format as a whole number times a power of two; rational numbers (such as 0.1, which is 1/10) whose denominator is not a power of two cannot be exactly represented. 
    15.       */ 
    16.   function chk_ans() 
    17.   { 
    18.    alert(0.1 + 0.2); //Not 0.3 
    19.   } 
    20.  </script> 
    21.  
    22. </body> 
    23.  
    24. </html>
    Problems of floating point number:- JavaScript Problems of floating point number:- JavaScript Reviewed by Network security on November 05, 2019 Rating: 5

    No comments:

    Useful Information

    Powered by Blogger.