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:


   
      JavaScript toFixed() Method
   
   
      
   

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:


   
      
   

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

501 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements