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:
Just use the following short function to get the result you need:
function pad2(number) {
return (number < 10 ? '0' : '') + number
}
Improved version of previous answer:
var result = [...Array(12)].map((_, i) => zeroFill(i + 1, 2));
function zeroFill(num, size) {
let s = num + '';
while (s.length < size) s = `0${s}`;
return s;
}
console.log(result)
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.
function padLeft(a, b) {
var l = (a + '').length;
if (l >= b) {
return a + '';
} else {
var arr = [];
for (var i = 0; i < b - l ;i++) {
arr.push('0');
}
arr.push(a);
return arr.join('');
}
}
function pad(d) {
return (d < 10) ? '0' + d.toString() : d.toString();
}
pad(1); // 01
pad(9); // 09
pad(10); // 10
String("0" + x).slice(-2);
where x
is your number.