Angular2 or TypeScript Left padding a string with zeros

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

I know that I can write my own logic. But I'm looking for an implicit use function that can use it.

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

Just like java

String.format("%010d", Integer.parseInt(mystring)); 
+18
source share
6 answers

You can create your own function for this. To format a number, you first need to convert it to a string.

 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 several better and more efficient ways to do this. See the discussion in this answer: fooobar.com/questions/20861 / ... (I recommend reading most of the answers provided if you have time)

Update: ECMAScript 2017 now has support for filling in a string

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

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

+29
source

Since Angular v4 has a DecimalPipe that makes it easy to add leading zeros: https://angular.io/api/common/DecimalPipe

In your html you can use something like:

{{ myNumber | number:'2.0' }}

+12
source

With the latest Typescript you can do:

 let myStr:string = padLeft('123', '0', 6); // '000123' padLeft(text:string, padChar:string, size:number): string { return (String(padChar).repeat(size) + text).substr( (size * -1), size) ; } 
+4
source
 public padIntegerLeftWithZeros(rawInteger: number, numberOfDigits: number): string { let paddedInteger: string = rawInteger + ''; while (paddedInteger.length < numberOfDigits) { paddedInteger = '0' + paddedInteger; } return paddedInteger; } public zeroPadIntegerLeft3Digits(rawInteger: number): string { return this.padIntegerLeftWithZeros(rawInteger, 3); } 
+1
source

You can use one of the following templates in HTML

 {{ ("00" + 9).slice(-2) }} // 09 

Or

 {{ 9 | number: '2.' }} // 09 

Or in the TS component code file

 var x = ("00" + 9).slice(-2); 
+1
source

You can create a pipe for this

 {{ID |LeftPadFilter: ID}} import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'LeftPadFilter', pure: false }) export class LeftPadFilter implements PipeTransform { transform(item: string): string { return (String('0').repeat(4) + item).substr((4 * -1), 4); } } 
0
source

Source: https://habr.com/ru/post/1012518/


All Articles