Round to n decimal places

Round to n decimal places, with zero padding.

by secretgspot

JavaScript

function roundNumber(num, dec) {
  var result = String(Math.round(num*Math.pow(10,dec))/Math.pow(10,dec));
  if(result.indexOf('.')<0) {result+= '.';}
  while(result.length- result.indexOf('.')<=dec) {result+= '0';}
  return result;
}

document.write(roundNumber(1.234,2));
document.write('<br/>');
document.write(roundNumber(0.99999,2));