How to format a rounded number to N decimals using JavaScript?

JavascriptWeb DevelopmentFront End Technology

Use the toFixed() method to format a rounded number to N decimals. The toFixed() method formats a number with a specific number of digits to the right of the decimal.

Example

You can try to run the following code to form a rounded number to N decimals −

Live Demo

<html>
   <head>
      <title>JavaScript toFixed() Method</title>
   </head>
   <body>
      <script>
         var num = 15;
         document.write("num.toFixed() is : " + num.toFixed());
         document.write("<br />");

         document.write("num.toFixed() is : " + num.toFixed(2));
         document.write("<br />");

         document.write("num.toFixed() is : " + num.toFixed(1));
         document.write("<br />");
      </script>
   </body>
</html>

Output

num.toFixed() is : 15
num.toFixed() is : 15.00
num.toFixed() is : 15.0
raja
Published on 03-Feb-2018 17:26:34
Advertisements