Zero pad in Typescript / Javascript

Just today I was working some code and needed to have my numbers front padded with zeros.  I did a quick check on the internet figuring "Oh, this should be common place".  Silly me, not at all.  I found some examples of regex and other crazy string manipulation. 

This was the coolest one I found on StackOverflow.  But I didn't need anything super generic.

function pad(n, width, z) {
  z = z || '0';
  n = n + '';
  return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n;
}

I just needed to pad numbers so I could format out the time for consumption by the date routine.  Basically I wanted to do some time math.  I didn't care about the date, but the Date object offered the functions I needed.  I only need a way to get my time into the Date object.  The Date object required the time to have zero padding.  For example 5 minutes after the hour needs to be put into Date object as 05

Easy way to get the padding:

            let hourString = (100 + Math.floor(remindMinute/60)).toString();
            let minuteString = (100  +  (remindMinute%60)).toString();
            let timeString = hourString.substring(1) + ':' + minuteString.substring(1);

Since the 100 is added to the hours or minutes you end up with numbers like 105 for 5 o'clock.  Substring that and you have '05'.

So if you ever need quick padding on a number with leading zeros you can use a similar trick.

 

 

Add comment