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


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

Updated on: 17-Jun-2020

294 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements