Computer >> Computer tutorials >  >> Programming >> Javascript

Is 'floating-point arithmetic' 100% accurate in JavaScript?


floating-point arithmetic is not always 100% accurate in javascript. For suppose take 1/3 i.e 0.33333..... Here the value 0.333.... will round at an unknown point. So if we add it with another value, whose value is also decimal we will not get the intended result. So we can conclude that when two decimals were added there will be rounding errors, but fortunately, those errors are quite small such that the actual code result will not be affected.

In the following example, when 0.3 is added with 0.6 the result must be 0.9 but since there are rounding errors the resulted value is not the intended value as shown in the output.

Example

<html>
<body>
   <p id="F-P-A"></p>
   <script>
      var err = 0.3 + 0.6;
         document.getElementById("F-P-A").innerHTML = "0.3 + 0.6 = " + err;
   </script>
</body>
</html>

Output

0.3 + 0.6 = 0.8999999999999999


In the following example, when 0.2 and 0.1 were added the intended result is 0.3 but because of rounding error, the intended value is not the resulted value.

Example

<html>
<body>
   <p id="F-P-A"></p>
   <script>
      var err = 0.2 + 0.1;
      document.getElementById("F-P-A").innerHTML = "0.2 + 0.1 = " + err;
   </script>
</body>
</html>

Output

0.2 + 0.1 = 0.30000000000000004