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:

function pad(input:number):string{
return input < 10 ? "0" + input : "" + input;
}
view raw zeropad.ts hosted with ❤ by GitHub

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

const hours = 1;
const minutes = 1;
const seconds = 1;
const time = `[${pad(hours)}:${pad(minutes)}:${pad(seconds)}]`);
// resutls in string '[01:01:01]';

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:
function pad(input:number, digits:number):string{
let target = `${input}`;
return target.padStart(digits,'0');
}
view raw zeropadany.ts hosted with ❤ by GitHub

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

const year = 2022;
const month = 4;
const day = 1;
const hour = 7;
const min = 3;
const sec = 9;
const millisec = 40;
let timestamp = `[${year}-${pad(month,2)}-${pad(day,2)} ${pad(hour,2)}:${pad(min,2)}:${pad(sec,2)}:${pad(milisec,3)}]`;
// timestamp value : '[2022-04-01 07:03:09:040]'