Home / Pad a number with leading zeroes in Javascript – Improved

Pad a number with leading zeroes in Javascript – Improved

A couple of weeks back I posted how to pad a number with leading zeroes in Javascript as a lead-in to a post about how to format a date time in Javascript in database format. The original post used a while() loop to add zeroes on to the string but as pointed out to me by Greg Jorgensen it’s not very efficient so I present his solution here.

My solution looked like this:

function pad(number, length) {
    var str = '' + number;
    while (str.length < length) {
        str = '0' + str;

    return str;


Greg’s solution looks like this:

function pad(n, len) {
    s = n.toString();
    if (s.length < len) {
        s = ('0000000000' + s).slice(-len);

    return s;

Obviously with Greg’s solution you need to make sure the ‘0000000000’ part is big enough for your purposes.

When just calling this function once the time difference between the two is negligible but as programmers we always need to do things as efficiently as we can. Running the two functions above 100,000 times each to get an idea of the time difference yielded the following results (each test was run several times):

pad(10,3) – my solution took about 160ms on average. Greg’s solution 210ms on average.

pad(10,7) – my solution took about 415ms on average. Greg’s about 214ms.

pad(10, 10) – my solutiontook about 615ms on average. Greg’s 215ms.

I’m not sure why his took longer as the padding got greater but then it wasn’t a very scientific sample. There’s no surprise that while fast for a small pad, mine took longer and longer as the pad got bigger.

This still doesn’t deal with negative numbers but I’ll look at the solution for this in my next Javascript post on Tuesday. As I’ve mentioned previously this solution was created for padding a whole number so it’s two digits long for the purpose of creating a database format date and time.