What is toFixed() in Javascript?

toFixed() is a Number method that is used to format a number using fixed-point notation. toFixed() formats a number to a given length after the decimal point by rounding off to reduce the length or by adding zeros to increase the length.

Declaration

The toFixed() method is declared as follows:

num.toFixed(len)
  • num: The number to be formatted using fixed-point notation.
  • len: The number of digits after the decimal point in which num will be formatted. len is an optional parameter.

Note:

  • If len is not passed as a parameter, the default len is len = 0. The number is rounded to a whole number.
  • len must be in the range 1 to 100. Otherwise, RangeError is thrown.

Return value

The toFixed() method returns a string that represents the number num with len digits after the decimal point.

Browser compatibility

The toFixed() method is supported by the following browsers:

  • Edge
  • Firefox
  • Google Chrome
  • Opera
  • Safari

Example

Consider the code snippet below, which demonstrates the use of the toFixed() method:

var num = 15.199
console.log("15.199 to precision of no length is: ",num.toFixed());
console.log("15.199 to precision of length 3 is: ",num.toFixed(1));
console.log("15.199 to precision of length 7 is: ",num.toFixed(7));

Explanation

A number num is initialized with num = 15.199 in line 1.

  • line 3: The toFixed() method is not passed the input parameter, so num is simply converted to a whole number.
  • line 5: len = 1 is passed to the toFixed() method, so the digits after the first decimal place are rounded off.
  • line 7: len = 7 is passed to the toFixed() method, so 4 zeros are added to make 7 decimal places.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved