Description
The JavaScript Number method toFixed()
returns a string representing the given number in fixed-point notation.
- It returns a new string and doesn't change the original number.
- It is commonly used to convert a number to its fixed-point notation.
Syntax
The method toFixed()
has the below syntax, where num
is a string.
num.toFixed(digits)
Parameters
The method allows the below parameters.
digits
(optional)
- It is a value between 0 and 100 that represents the number of digits to appear after the decimal point.
- The default value is 0.
- If the value is not between 0 and 100, the method throws a
RangeError
.
Result
Returns a string that represents the given number in fixed-point format.
Example 1: Using the Method
The below example shows the basic usage of the method.
var num = 123.45678;
// Without digits argument
document.write(num.toFixed()); // Prints: 123
// With digits argument
document.write(num.toFixed(0)); // Prints: 123
document.write(num.toFixed(2)); // Prints: 123.46 -> here the value is rounded
document.write(num.toFixed(5)); // Prints: 123.45678
document.write(num.toFixed(10)); // Prints: 123.4567800000 -> zeroes padded to get required decimal places
// Using exponential values
document.write((1.2345e10).toFixed(2)); // Prints: 12345000000.00
document.write((1.2345e-10).toFixed(2)); // Prints: 0.00
// Using negative values
document.write((-1.2345).toFixed(2)); // Prints: -1.23
Output:
123
123
123.46
123.45678
123.4567800000
12345000000.00
0.00
-1.23
Example 2: Method Returns RangeError
If the argument digits
is not between 0 and 100, the method returns a RangeError
.
var num = 123.45678;
// Throws RangeError
document.write(num.toFixed(-1)); // Throws RangeError
document.write(num.toFixed(101)); // Throws RangeError
document.write(num.toFixed(Infinity)); // Throws RangeError
Output:
RangeError: toFixed() digits argument must be between 0 and 100
Example 3: Using the Method with Digits = NaN
If the argument digits
is NaN, the method ignores the value and executes as if the argument is omitted.
var num = 123.45678;
// Using digits NaN
document.write(num.toFixed(NaN)); // Prints: 123
document.write(num.toFixed("abc")); // Prints: 123
Output:
123
123
Overall
The JavaScript Number method toFixed()
returns a string representing the given number in exponential format.