Angular2 or TypeScript Left padding a String with Zeros

后端 未结 7 1809
無奈伤痛
無奈伤痛 2020-12-16 09:42

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

相关标签:
7条回答
  • 2020-12-16 10:21

    You can create a Pipe for that

    {{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(2) + item).substr((2 * -1), 2);
        }
    }
    
    0 讨论(0)
  • 2020-12-16 10:22

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

    0 讨论(0)
  • 2020-12-16 10:22

    You can use one of below templates in HTML

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

    Or

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

    Or in component ts code file

    var x = ("00" + 9).slice(-2);
    
    0 讨论(0)
  • 2020-12-16 10:26

    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' }}
    
    0 讨论(0)
  • 2020-12-16 10:26

    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) ;
    }
    
    0 讨论(0)
  • 2020-12-16 10:29

    if i want to pad "0" at the start and want the length of the String str to be 9:

    str.padStart(9 ,"0")
    
    0 讨论(0)
提交回复
热议问题