Learn how to round to 2 decimal places in javascript

Learn how to precisely round off a given number to 2 decimal places in javascript.

A number can be rounded off to upto 2 decimal places using two different approaches in javascript.

Method 1: Using toFixed() method.

The Number.toFixed() method takes an integer as an input and returns the the given number as a string in which the fraction is padded to the input integers length.

The input integer ranges from 0 to 20.

Input:
let a = 3.14159265359;
let b = a.toFixed(2);
console.log(b);

Output:
"3.14"

It rounds off to nearest ceiling or flooring value based on the later digits.
If it is greater than 5 then it will take the ceiling value else it will take the flooring value.


Method 2: Using Math.round() method to round off the number to 2 decimal places in javascript.

The Math.round() method is used to round to the nearest integer value. It takes number which needs to be rounded off as an input.

To round off any number to any decimal place we can use this method by first multiplying the input number with 10 ^ decimal place, so in our case it is 2 that is Math.round(3.14159265359 * (10 ^ 2)) and then divide it by 10 ^ decimal place like Math.round(3.14159265359 * (10 ^ 2)) / (10 ^ 2) so it will now round off the given number to 2 decimal places.

It returns the output as a number.

Input:
Math.round(3.14159265359 * 100) / 100

Output:
3.14

We can create our custom function to round off to any digit.

let roundOff = (num, places) => {
  const x = Math.pow(10,places);
  return Math.round(num * x) / x;
}
Input:
console.log(roundOff(3.14159265359, 2));

output:
3.14