Round to 2 decimal places in JavaScript

Round to 2 decimal places in javascript

In this post, we will see how to round to 2 decimal places in javascript.

Using Math.Round() to Round to 2 Decimal Places in JavaScript

You can use Math.round() function to round number to 2 decimal places in javascript.

You need to multiply number by 100, apply Math.round() and then divide by 100.

Output:

14.34

but, this code won’t work correctly for numbers like 1.005. Let’s see with example.

Output:

1

To correct this behavior, you can add Number.EPSILON to number before multiplying it to 100.

Output:

1.01

As you can see, we got correct rounding in this scenario.

Using Number.toFixed() to round to 2 decimal places in js

You can use Number.toFixed() to round number to 2 decimal places. You need to pass the number of digits for which you want to round number.

Output:

1.00

As you can see, this does not work in some scenarios and it may not round as expected.
For example:

  • If input number is 1.1, then it will show output as 1.10.
  • If input number is 1.156, then it will show output as 1.15.

Write custom function to round to 2 decimal places in javascript

You can write a generic custom function to round number for 2 decimal places in javascript.

Here is the code:

Output:

1.23
1.01

In case, you want to make it generic for n decimal places. You can write function as below:

Output:

1.2
1.003

Create Round Prototype to Round to Two Decimal Places in JavaScript

You can also write round prototype to add this function to number and you can directly call round() method on the number.

Output:

1.23
1.03

That’s all about how to round to 2 decimal places in javascript.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *