Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)); 
like image 824
Partha Sarathi Ghosh Avatar asked Nov 21 '16 09:11

Partha Sarathi Ghosh


People also ask

How can I pad a string with zeros on the left?

leftPad() method to left pad a string with zeros, by adding leading zeros to string.


2 Answers

Since Angular v4 there is DecimalPipe which let's easily add leading zeros: https://angular.io/api/common/DecimalPipe

In your html, you can use then something like:

{{ myNumber | number:'2.0' }}

like image 44
maczos Avatar answered Sep 25 '22 18:09

maczos


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: https://stackoverflow.com/a/9744576/1734678 (I recommend reading most of the submitted answers if you got time)

Update: ECMAScript 2017 now has support for string padding

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

Check https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart

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

{{ myNumber | number:'2.0' }} 
like image 94
Evans M. Avatar answered Sep 22 '22 18:09

Evans M.