When working with numbers in JavaScript, there are many situations where you’ll want to round a number to two decimal places — for example, when dealing with prices, percentages, or measurements.
Fortunately, JavaScript makes this easy with the built-in .toFixed()
method.
In this quick guide, you’ll learn exactly how to round numbers to two decimal places in JavaScript, with simple examples you can copy and use right away!
Basic Example: Rounding a Number
Let’s start with a simple example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | <!doctype html> <html> <head> <meta charset="utf-8"> <title>JavaScript Round to 2 Decimals</title> </head> <body> <script> var number = 12.4528; // Step 1: Round the number to 2 decimal places number = number.toFixed(2); console.log(number); // Output: "12.45" (type: string) // Step 2: Convert the result back to a number number = Number(number); console.log(number); // Output: 12.45 (type: number) // Final shortcut: Combine both steps number = Number(number.toFixed(2)); console.log(number); // Output: 12.45 </script> </body> </html> |
Output
1 2 3 4 5 | 12.45 // string 12.45 // number 12.45 // number (final) |
As you can see, .toFixed(2)
rounds the number to two decimal places, but it returns a string, not a number.
If you need a real number (for calculations, comparisons, etc.), you should wrap it with Number()
like we did above.
Why Does .toFixed()
Return a String?
In JavaScript, the .toFixed()
method formats a number as text, which is why the output is a string.
This can be useful for display purposes (like showing a formatted price), but if you want to continue doing mathematical operations, you’ll need to convert it back to a number.
Pro Tip: A One-Liner Solution
If you want a cleaner, one-line version without extra steps:
1 2 3 4 | let roundedNumber = Number((12.4528).toFixed(2)); console.log(roundedNumber); // Output: 12.45 |
Simple and efficient!
Conclusion
Rounding numbers in JavaScript is easy once you understand how .toFixed()
and Number()
work together.
Always remember:
.toFixed()
formats a number with fixed decimals but returns a string.- Use
Number()
if you need the value to stay a true number.
Whether you’re building a shopping cart, calculating grades, or formatting financial reports, mastering this small trick will make your code cleaner and more reliable!