Skip to main content

A JavaScript function that will round a number to the specified decimal position.

var padZero = function (rounded, places) {
  var val = rounded.toString();
  var point = val.indexOf('.');

  if (point == -1) {
    len = 0;
    val += places > 0 ? '.' : '';
  } else {
    len = val.length - point - 1;
  }

  var pad = places - len;
  if (pad > 0) {
    for (var counter = 1; counter <= pad; counter++) {
      val += '0';
    }
  }
  return val;
};

var roundDecimals = function (number, decimals) {
  var temp = Math.round(number * Math.pow(10, decimals)) / Math.pow(10, decimals);
  return padZero(temp, decimals);
};

roundDecimals(0.1212342342343, 2); // returns "0.12"