Format a Number, Exactly Two in Length?

Just use the following short function to get the result you need:

function pad2(number) {
    return (number < 10 ? '0' : '') + number
}

String("0" + x).slice(-2);

where x is your number.


https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart

String(number).padStart(2, '0')

Update

This answer was written in 2011. See liubiantao's answer for the 2021 version.

Original

function pad(d) {
    return (d < 10) ? '0' + d.toString() : d.toString();
}

pad(1);  // 01
pad(9);  // 09
pad(10); // 10

Tags:

Javascript