Number.prototype.toFixed
Formats a number with a given number of decimal places.
Available since: ES3
Syntax
number.toFixed(digits)Parameters
| Parameter | Type | Description |
|---|---|---|
| digits | number | Optional. How many decimal places to keep; 0 by default. |
Return value
stringA string holding the rounded number.
Examples
Two decimal places:
console.log((3.14159).toFixed(2));
console.log((2.5).toFixed(2));Output:
3.14
2.50The result is a string, not a number:
console.log(typeof (3.14159).toFixed(2));Output:
stringNotes
Wrap the result in Number() to get a number again. Trailing zeros are lost in the process.
See also
- Math.round — Rounds a number to the nearest integer.
- parseInt — Converts a string to an integer.
- Number.prototype.toLocaleString — Formats a number by language rules: digit grouping, currency, percent.
- Intl.NumberFormat — Formats numbers, currencies, percents and units by language rules.
Related recipes
In the tutorial
- Numbers — Numbers in JavaScript — integers and fractions, rounding, the Math object, toFixed and the special values Infinity and NaN.