Table of Contents
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.
1 2 3 4 5 |
var num=14.34242; var roundedNum=Math.round(num*100)/100; console.log(roundedNum); |
Output:
but, this code won’t work correctly for numbers like 1.005
. Let’s see with example.
1 2 3 4 5 |
var num=1.005; var roundedNum=Math.round(num*100)/100; console.log(roundedNum); |
Output:
To correct this behavior, you can add Number.EPSILON to number before multiplying it to 100.
1 2 3 4 5 |
var num=1.005; var roundedNum=Math.round((num + Number.EPSILON)*100)/100; console.log(roundedNum); |
Output:
As you can see, we got correct rounding in this scenario.
Further reading:
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.
1 2 3 4 5 |
var num=1.005; var roundedNum=num.toFixed(2); console.log(roundedNum); |
Output:
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 as1.10
. - If input number is
1.156
, then it will show output as1.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:
1 2 3 4 5 6 7 8 |
function roundNumberTo2Decimal(n) { return +(Math.round(n + "e+2") + "e-2"); } console.log(roundNumberTo2Decimal(1.225)); console.log(roundNumberTo2Decimal(1.005)); |
Output:
1.01
In case, you want to make it generic for n decimal places. You can write function as below:
1 2 3 4 5 6 7 8 |
function roundNumberToNDecimal(n,places) { return +(Math.round(n + "e+" + places) + "e-" + places); } console.log(roundNumberToNDecimal(1.225,1)); console.log(roundNumberToNDecimal(1.00315,3)); |
Output:
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.
1 2 3 4 5 6 7 8 |
function roundNumberToNDecimal(n,places) { return +(Math.round(n + "e+" + places) + "e-" + places); } console.log(roundNumberToNDecimal(1.225,1)); console.log(roundNumberToNDecimal(1.00315,3)); |
Output:
1.03
That’s all about how to round to 2 decimal places in javascript.