How to deal with floating point number precision in JavaScript?

JavascriptWeb DevelopmentFront End Technology

To handle floating point number precision in JavaScript, use the toPrecision() method. It helps to format a number to a length you can specify.

Example

Live Demo

<!DOCTYPE html>
<html>
   <body>
      <script>
         var num = 28.6754;
         document.write(num.toPrecision(3));
         document.write("<br>"+num.toPrecision(2));
         document.write("<br>"+num.toPrecision(5));
      </script>
   </body>
</html>

Output

28.7
29
28.675
raja
Published on 03-Feb-2018 17:57:42
Advertisements