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.
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 defaultlen
islen = 0
. The number is rounded to a whole number.len
must be in the range 1 to 100. Otherwise, RangeError is thrown.
The toFixed()
method returns a string that represents the number num
with len
digits after the decimal point.
The toFixed()
method is supported by the following browsers:
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));
A number num
is initialized with num = 15.199
in line 1.
toFixed()
method is not passed the input parameter, so num
is simply converted to a whole number.len = 1
is passed to the toFixed()
method, so the digits after the first decimal place are rounded off.len = 7
is passed to the toFixed()
method, so 4 zeros are added to make 7 decimal places.Free Resources