Saturday, April 23, 2022

Zero padding string representations of numeric values in TypeScript

Recently needed to look into converting numeric values into zero padded strings, on account of needing to create a timestamp string that could be used in log statements in typescript. Generally speaking, I wanted to be able to create a string in the following format:

[2022-04-23 12:05:01:074]

Came up with the following code as a start:

It's good, converts a numeric value to a zero padded string. I can use this utility function as follows:

It's a pretty basic start, and this pad() routine would be sufficient if i wanted to pad month, day, hour, minute, second values. However this solution won't work well if I'm trying to create a timestamp value, since it will not help out when creating the millisecond string representation. The millisecond field will require 3 digit resolution, and the pad() utility above will only handle 2 digit values.

Thankfully the String object in JavaScript has a useful padStart() utility method that will come in handy ( String.prototype.padStart() ).

This method allowed me to update the pad utility to handle any length numeric value:

I can now use this utility method as follows to generate a full timestamp value with milliseconds: