Partha Sarathi Ghosh Partha Sarathi Ghosh - 24 days ago 8
TypeScript Question

Angular2 or TypeScript Left padding a String with Zeros

I have a number let say 9. But I need it as String "09".

I know i can write my own logic. But I am looking for a implicit util function which can pad it.

I am using angular2 with TypeScript. Looking for something like this.

Just Similar like java

String.format("%010d", Integer.parseInt(mystring));

Answer Source

You can create your own function for this. To format the number you will have to convert it to a string first.

function pad(num, size) {
    let s = num+"";
    while (s.length < size) s = "0" + s;
    return s;
}

TypeScript

pad(num:number, size:number): string {
    let s = num+"";
    while (s.length < size) s = "0" + s;
    return s;
}