Angular2 or TypeScript: Left padding a String with Zeros

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;
}

Edit: There are a couple of better and more performant ways to do this.
See the discussion in this answer (I recommend reading most of the submitted answers if you got time): https://stackoverflow.com/a/9744576/1734678

Update: ECMAScript 2017 now has support for string padding:

str.padStart(targetLength [, padString])
str.padEnd(targetLength [, padString])

Check out padStart‘s documentation.

EDIT: As mentioned by others, since Angular 4 you can use this:

{{ myNumber | number:'2.0' }}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)