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 whichnumwill be formatted.lenis an optional parameter.
Note:
- If
lenis not passed as a parameter, the defaultlenislen = 0. The number is rounded to a whole number.lenmust 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.199console.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, sonumis simply converted to a whole number. - line 5:
len = 1is passed to thetoFixed()method, so the digits after the first decimal place are rounded off. - line 7:
len = 7is passed to thetoFixed()method, so 4 zeros are added to make 7 decimal places.
Free Resources
Copyright ©2026 Educative, Inc. All rights reserved