Manso Trick: Pad a number with leading zeroes in javascript

I was missing a simple and elegant method for padding a number with leading zeroes in javascript.

A typical example of leading zeroes is when you want to show the current time and you want the time to be formatted like hh:mm. There is no problem when it’s 12:40, but when is five minutes past one, you get 1:5, which is not what you would expect. You want it formatted like 01:05. The same happens with dates and in several other situations.

Yesterday I found the best solution I’ve seen for this problem. Before that, let’s see possible solutions.

Usually, needing only one zero, I would do something like:

h = (h < 10) ? ("0" + h) : h;

This is not bad at all, but is not elegant. The problem is, what if we want it to be formatted with 3 digits? Then, using the same schema, we can end up with something like:

h = (h < 100) ? ( (h >= 10) ? ("0" + h) : ("00" + h) ) : h;

Man, this is ugly and unreadable!! Maybe it will improve with an if/else, but it will be bad anyway. Probably if you need to do something like that, you will create a function that will handle this problem and then, you will call that function saying you want h padded with 3 zeros. But there is another solution that does not require you to use or create such a funciton…

Have a look for two digit and three digit:

("0" + h).slice (-2);  // devolverá "01" si h=1; "12" si h=12
("00" + h).slice (-3); // "001" si h=1; "012" si h=12;"123" si h = 123

I don’t know what are you thinking after seeing this solution, but I got flashed when I saw it. Just amazing!

Let’s explain what’s going on. The code above only concatenates the “00″ with the number we want to format (e.g: “00″ + 12 = “0012″) and then, we get the last three digits using the slice string function (that’s why you have a -3). Guess what? The last three characters are “012″ which is the string we want.

Of course this solution is not only limited to leading zeroes, you can use it with leading spaces, or whatever character you want.

Sources:

Update: Milan Adamovsky has created a web page http://jsperf.com/zero-padding where you can check the performance issues of several functions to pad with zeroes, and you can try it directly in your browser ;)

Trackback URL

, , ,

13 Comments on "Manso Trick: Pad a number with leading zeroes in javascript"

  1. Amnon
    21/09/2010 at 1:42 am Permalink

    Thanks – if there isn’t a native way of doing this in JavaScript then this is the most elegant method I’ve seen so far.

  2. Pau Sánchez
    22/09/2010 at 12:53 pm Permalink

    Trust me, there is no native way

  3. Camilo Martin
    08/12/2010 at 11:33 am Permalink

    This should be coded as a while loop. Make a function for it :)

  4. Bjorne Bjornson
    02/01/2011 at 7:18 am Permalink

    Reminds me of the early there’s-more-than-one-way-to-do-it Perl days. Will definitely break large teams’ and projects’ necks.

  5. Pau Sánchez
    06/01/2011 at 3:16 pm Permalink

    @Bjorne Bjorson I’m totally agree with you, doing that in the code is totally a mistake, but you can always comment the code…

    This is a quick-and-dirty-way of padding zeroes.

    PS: OK, commenting the code is probably not the best solution (nobody forces you to say what you do… and even if you do comment, it won’t make people understand what happens underneath – like in perl), the best solution would be to create a “padzeroes” function but for doing that, you will have to use a loop, so there are other solutions more simple to understand that using slice… so again, this is a quick and dirty way of padding zeroes, but is up to you and your wiseness to decide when to use this trick. I know not everybody is wise enough to know when to use tricks… even sometimes, I doubt I am wise enough to use them… but sometimes, sometimes, this tricks are useful and a great way of solving a common problem.

    If everyone knew about this trick, it will be common sense to use this, so it won’t be hard to understand to anybody (maybe the first time)… it will be great to have a trim/strip and a pad function native in javascript… that would be the best, most simple and most elegant solution.

  6. Gary F
    14/03/2011 at 6:29 am Permalink

    I like it, Pau. Very short and sweet piece of code. I’m commenting my use of it just in case colleagues scratch their head if they need to modify my code in future. He-he!

  7. John
    06/04/2011 at 7:49 am Permalink

    The best I ever seen; why don’t you post it on stackoverflow too, I’m sure they will appreciate :-)

    Gratias,

  8. Milan Adamovsky
    13/04/2011 at 11:40 am Permalink

    I really liked the l33t code, but performance wise this is what it yields:

    http://jsperf.com/zero-padding

  9. ola l martins
    09/05/2011 at 11:33 pm Permalink

    i prefer this:

    ('000' + h.toString()).substr(h.toString().length);

    example:
    ’000′ + ’3′ => ’0003′ => start position from the length of ’3′ => 1 and by leaving the length parameter for substr, everything til the end is retreived => ’003′

  10. Pau Sanchez
    15/05/2011 at 8:17 am Permalink

    @ola I thing the code you put on the previous comment is a little larger to write, but more clear to understand for any programmer.
    Thanks!

  11. Simon
    29/11/2011 at 9:34 pm Permalink

    Or, recursively:

    function pad(v,s,c) {v+=”;return(v.length<s)?(c||'0')+pad(v,s-1,c):v}

    v = value to pad
    s- size of resulating string
    \c char to pad with (defaulst to '))')

    Cheers

  12. Peter
    14/11/2012 at 6:25 am Permalink

    ([1e10] + this).slice(-size) is even more elegant (changing 10 as required, of course).

    To explain if it isn’t obvious, 1e10 creates 10000000000, the array get converted into “10000000000″ when a string is concatenated, the rest is the same.

  13. Kirk Bushell
    08/05/2013 at 9:59 pm Permalink

    This is gorgeous, awesome solution! :)

Hi Stranger, leave a comment:

ALLOWED XHTML TAGS:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Subscribe to Comments