How to Use toFixed in JavaScript: Syntax and Examples
In JavaScript, use the
toFixed() method on a number to format it as a string with a fixed number of decimal places. For example, num.toFixed(2) returns a string with 2 decimals. This method rounds the number and returns a string, not a number.Syntax
The toFixed() method is called on a number and takes one optional argument:
- digits (optional): The number of digits to appear after the decimal point. It must be between 0 and 100, inclusive.
The method returns a string representing the number rounded to the specified decimal places.
javascript
number.toFixed(digits)
Example
This example shows how to use toFixed() to format a number with 2 decimal places and how it rounds the number.
javascript
const num = 3.14159; const formatted = num.toFixed(2); console.log(formatted);
Output
3.14
Common Pitfalls
Common mistakes include expecting toFixed() to return a number instead of a string, and passing invalid arguments.
- Wrong: Using the result as a number directly can cause unexpected behavior.
- Right: Convert the string back to a number if needed using
parseFloat(). - Passing a negative or non-integer argument throws a
RangeError.
javascript
const num = 2.5; const wrong = num.toFixed(2) + 1; // '2.50' + 1 = '2.501' const right = parseFloat(num.toFixed(2)) + 1; // 2.5 + 1 = 3.5 console.log(wrong); console.log(right);
Output
2.501
3.5
Quick Reference
| Usage | Description |
|---|---|
| number.toFixed(0) | Rounds to nearest whole number, returns string |
| number.toFixed(2) | Formats number with 2 decimal places, returns string |
| parseFloat(number.toFixed(n)) | Converts formatted string back to number |
| number.toFixed() | Defaults to 0 decimal places |
Key Takeaways
Use
toFixed() to format numbers as strings with fixed decimal places.toFixed() returns a string, so convert back to number if needed.The argument must be an integer between 0 and 100; otherwise, it throws an error.
It rounds the number to the specified decimal places.
Avoid adding numbers directly to
toFixed() results without conversion.