Sometimes you could have the need to print out numbers in a predefined format.

For example if you want to print out the current time and you want the time to be formatted like hh:mm. You will have no problem when it’s 10:05, but when it is five minutes past ten you will have something like 10:5, or if it is 10 past five you will have 5:10.

These are not so good results. You should have them formatted as 10:05 and 05:10.

I’ve written the following simple javascript function to apply a leading zero if it is needed.

function paddingNumbers(num, size)
{
    return ('0' + num).substr(-size);
}
where size is the number of characters you want to print out, and num is the number you want to print out.

javascript_logo
Naturally the above function can be extended to apply a variable number of leading zeros.

function paddingNumbers(num, size)
{
    var zeroString="";
    for(i=0; i<size; i++)
    {
        zeroString = zeroString+0;
    }
    return (zeroString + num).substr(-size);
}
Gg1