I have an integer that is less then 100 and is printed to an HTML page with JavaScript. How do I format the integer so that it is exactly two digits long? For example:
A direct way to pad a number to the left in Javascript is to calculate the number of digits by log base 10. For example:
function padLeft(positiveInteger, totalDigits) {
var padding = "00000000000000";
var rounding = 1.000000000001;
var currentDigits = positiveInteger > 0 ? 1 + Math.floor(rounding * (Math.log(positiveInteger) / Math.LN10)) : 1;
return (padding + positiveInteger).substr(padding.length - (totalDigits - currentDigits));
}
The rounding factor fixes the problem that there is no way to get an exact log of powers of 10, for example Math.log(1000) / Math.LN10 == 2.9999999999999996 Of course one should add validation of the parameters.