Round a Number to 2 Decimal Places in JavaScript

  1. Use the .toFixed() Method to Round a Number To2 Decimal Places in JavaScript
  2. Use the Math.round() Function to Round a Number To2 Decimal Places in JavaScript
  3. Use Double Rounding to Round a Number To2 Decimal Places in JavaScript
  4. Using the Custom Function to Round a Number To2 Decimal Places in JavaScript

This tutorial introduces how to round a number to2 decimal places in JavaScript.

Use the .toFixed() Method to Round a Number To2 Decimal Places in JavaScript

We apply the .toFixed() method on the number and pass the number of digits after the decimal as the argument.

var numb = 12312214.124124124;
numb = numb.toFixed(2);

This method does not yield accurate results in some cases, and there are better methods than this. If a number rounds of 1.2, then it will show 1.20. If a number like 2.005 is given, it will return 2.000 instead of 2.01.

Use the Math.round() Function to Round a Number To2 Decimal Places in JavaScript

We take the number and add a very small number, Number.EPSILON, to ensure the number’s accurate rounding. We then multiply by number with 100 before rounding to extract only the two digits after the decimal place. Finally, we divide the number by 100 to get a max of 2 decimal places.

var numb= 212421434.533423131231;
var rounded = Math.round((numb + Number.EPSILON) * 100) / 100;
console.log(rounded);

Output:

212421434.53

Although This method improves over .toFixed(), it is still not the best solution and will also not round of 1.005 correctly.

Use Double Rounding to Round a Number To2 Decimal Places in JavaScript

In this method, we use the .toPrecision() method to strip off the floating-point rounding errors introduced during the intermediate calculations in single rounding.

function round(num) {
    var m = Number((Math.abs(num) * 100).toPrecision(15));
    return Math.round(m) / 100 * Math.sign(num);
}

console.log(round(1.005));

Output:

1.01

Using the Custom Function to Round a Number To2 Decimal Places in JavaScript

function roundToTwo(num) {
    return +(Math.round(num + "e+2")  + "e-2");
}
console.log(roundToTwo(2.005));

This custom function takes care of all the corner cases, and rounding of decimals like 1.005 is handled well by this function.

Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - JavaScript Number

  • Generate a Random Number Between Two Numbers in JavaScript