JavaScript

How to Round a Number to 2 Decimal Places in JavaScript (With Examples)

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:


Output

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:

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!

Leave a Comment