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



