When working with numbers in JavaScript especially in financial, scientific, or UI-based applications precision matters. That’s where the .toFixed() method comes in.
In this guide, you'll learn what .toFixed() is, how it works, and when to use it to round or format decimal numbers.
What is .toFixed() in JavaScript?
.toFixed() is a JavaScript number formatting technique that uses fixed-point notation. It returns a string containing the number with the specified number of digits after the decimal point.
Syntax:
num.toFixed(digits)
num: The number to formatdigits(optional): The number of digits to appear after the decimal point (0 to 100)
What .toFixed() Does:
Rounds the number to the nearest value based on the decimal places specified
Returns the result as a string (not a number)
Useful for currency, percentage, weight, or any formatted display
Common Scenarios Where .toFixed() Is Useful
Displaying prices or totals:
let price = 45.678; console.log(price.toFixed(2)); // "45.68"Showing percentages:
let completion = 0.9575 * 100; console.log(completion.toFixed(1) + "%"); // "95.8%"Weight or measurement formatting:
let weight = 63.456; console.log(weight.toFixed(0)); // "63"
More Examples:
Code | Output | Explanation |
|---|---|---|
|
| Rounded to 2 decimal places |
|
| Padded with zeros |
|
| No decimals shown |
|
| Fixes floating-point issues |
Sample Problem and Solution
🧩 Problem: A user enters the price of a product as 89.999. You want to display it as a currency format with two decimal places.
✅ Solution:
let userInput = 89.999;
let formattedPrice = userInput.toFixed(2);
console.log("Price: $" + formattedPrice); // Output: Price: $90.00
Important Notes:
.toFixed()always returns a string. Convert it back to a number withparseFloat()if needed.It rounds up or down depending on the value of the next decimal digit.
Conclusion
The .toFixed() function in JavaScript is a basic yet effective tool for precisely formatting integers. Whether you're creating a price page, analytics dashboard, or input validator, this technique guarantees that your statistics are clear, consistent, and easy to read.