Home / Pad a number to two digits with Javascript

Pad a number to two digits with Javascript

On Sunday I looked at how to pad a number with leading zeroes in Javascript and in this post look at a simpler function to pad a number to just two digits as if required for days and months, and hours, minutes and seconds.

Please note: this doesn’t work for negative numbers; it was designed specifically for padding with leading a zeros a number which will be used in date formats where negatives are not possible (there will be a post later this week about this). I’ll write another post to revise what’s here and will work with negative numbers.

Check out the original pad function in the previous post to see how to pad a number to any number of places. The following "pad2" function only ever pads the number to two places adding a leading zero if necessary. This makes it suitable for ensuring dates (days and months) and times (hours, minutes and seconds) are always two digits.

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

Some code to test the above:

document.write(pad2(0) + '<br />');
document.write(pad2(1) + '<br />');
document.write(pad2(2) + '<br />');
document.write(pad2(10) + '<br />');
document.write(pad2(15) + '<br />');

And the resulting output:

00
01
02
10
15

The reason I needed to pad numbers was for formatting dates and times in a text field in a web form for sending through to a database. I’ll show how to use the Javascript Date object to return the current date and time in a database ready format in my next Javascript post on Friday.

Post updated December 2nd 2009

This post was updated on December 2nd 2009 thanks to a suggestion by Hans Pufal. In my original post the return value type would be either a string or an integer depending if the value passed in was a single digit or double digit. Hans’ modification ensures a string type is always returned.