Skip to content
Advertisement

Format a Number, Exactly Two in Length?

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:

01
02
03

09
10
11
12

Advertisement

Answer

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
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement