How to round a number to a specific number of decimal places in JavaScript / JScript

If you will look at the documentation of Math.round() method, you'll see that it takes only 1 argument, which is the number that you want to round. The rounding method is going to round your number to the closes integer. If this doesn't sit well with you, you can use the function below to round any number to any decimal places.

function Round (number, decPlaces) {
   // multiply the number by the number of decimal place
   var newNumber = number * Math.pow(10, decPlaces);
 
   // round resulting number to the nearest integer
   newNumber = Math.round(newNumber);
 
   // divide rounded number by the number of decimal places
   newNumber = newNumber / Math.pow(10, decPlaces);
 
   // return the result
   return newNumber;
}

Hope this is helpful!

Comments