WEBDOOD.COM

Javascript Number ensureDecimalPlaces

by webdood on Nov.17, 2011, under Arrays, Javascript, Numbers

Needed a function ensure that a certain number of digits appeared after a decimal point today.

For instance 1.3 should be 1.300, 1 should be 1.000 etc.

Number.prototype.ensureDecimalPlaces = function( decimals ) {
  var tempString = this.toString(),
      pileOfPads = "000000000000000000000000",
      decimalLocation = tempString.indexOf('.');
  if (decimalLocation === -1) {
    retVal = tempString + '.' + pileOfPads.substring(0,decimals);
  } else {
    retVal = tempString + pileOfPads;
    retVal = retVal.substring(0,decimalLocation+decimals+1);
  }
  return retVal;
}

Example use:

var x = 12.3
console.log(x.ensureDecimalPlaces(3)) returns 12.300


Leave a Reply

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Blogroll

A few highly recommended websites...

  • A List Apart
  • Dive into HTML5
  • Javascript: The Good Parts
  • QuirksMode.org