JavaScript num.toFixed([digits]) method
The num.toFixed([digits])
method in JavaScript is used to convert a number to a string, representing the number in fixed-point notation. This method is useful for formatting numbers to a specific number of decimal places, which is often necessary for displaying currency or other precise values.
Syntax:
num
: The number you want to format.digits
(optional): An integer specifying the number of digits to appear after the decimal point. This value must be between0
and20
. If omitted, it defaults to0
, meaning the number will be rounded to the nearest integer.
Return Value:
- Returns a string representation of the number in fixed-point notation with the specified number of decimal places.
Example Usage:
Basic Usage:
Rounding Behavior:
- The method rounds the number based on the value of the digit immediately after the specified decimal places:
Using with Integers:
Handling Large Numbers:
Invalid Input:
- If the
digits
argument is outside the valid range (0-20), aRangeError
will be thrown:
- If the
Special Cases:
- If the number is
NaN
,Infinity
, or-Infinity
, the method will return the string representation of these values ("NaN"
,"Infinity"
, or"-Infinity"
).
Summary:
The num.toFixed([digits])
method is a straightforward way to format numbers to a specified number of decimal places in JavaScript. It is particularly useful for financial calculations and presenting data where precision is required. The method handles rounding and ensures that the output is always in string format, accommodating the specified number of decimal places.