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 point and returns a string representation.

Syntax

number.toFixed(digits)

Parameters

digits (optional): An integer specifying the number of digits after the decimal point. Must be in the range 0-100. Default is 0.

Return Value

Returns a string representation of the number with the specified number of decimal places.

Example

Here's how to format numbers to different decimal places:

<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(2) is : " + num.toFixed(2));
         document.write("<br />");

         document.write("num.toFixed(1) is : " + num.toFixed(1));
         document.write("<br />");
         
         // Example with decimal number
         var decimal = 3.14159;
         document.write("decimal.toFixed(2) is : " + decimal.toFixed(2));
         document.write("<br />");
         
         document.write("decimal.toFixed(4) is : " + decimal.toFixed(4));
      </script>
   </body>
</html>

Output

num.toFixed() is : 15
num.toFixed(2) is : 15.00
num.toFixed(1) is : 15.0
decimal.toFixed(2) is : 3.14
decimal.toFixed(4) is : 3.1416

Rounding Behavior

The toFixed() method rounds the number when necessary:

<html>
   <body>
      <script>
         var price = 19.456;
         document.write("Original: " + price);
         document.write("<br />");
         
         document.write("Rounded to 2 decimals: " + price.toFixed(2));
         document.write("<br />");
         
         document.write("Rounded to 1 decimal: " + price.toFixed(1));
         document.write("<br />");
         
         document.write("Rounded to 0 decimals: " + price.toFixed(0));
      </script>
   </body>
</html>

Output

Original: 19.456
Rounded to 2 decimals: 19.46
Rounded to 1 decimal: 19.5
Rounded to 0 decimals: 19

Key Points

  • toFixed() returns a string, not a number
  • If no parameter is provided, it defaults to 0 decimal places
  • The method performs rounding when necessary
  • Trailing zeros are added to reach the specified decimal places

Conclusion

The toFixed() method is the standard way to format numbers to a specific number of decimal places in JavaScript. It handles rounding automatically and always returns a string representation with the exact number of decimals specified.

Updated on: 2026-03-15T23:18:59+05:30

513 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements