Bill Gardner
Bill Gardner

Reputation: 196

Can Angular's Decimal Pipe Display 4 Integer Digits Without a Comma?

I am using Angular's Decimal Pipe to display line numbers generated from the index of a ngFor loop. I need to display digits up to 4 digits long (no decimals), but do not want a comma separation between the 3rd and 4th leading zero. Can this be configured via the Decimal pipe, or do I need to write a custom pipe?

    <div *ngFor="let line of message; let i = index">
      <pre>{{i + 1 | number:'3.0'}}&nbsp;{{line}}</pre>
    </div>

I want the line to display as such: 0001 Line Text Here 0002 More Line Text 0003 Event More Text

I'm getting: 0,001 Line Text Here 0,002 More Line Text 0,003 Event More Text

Upvotes: 1

Views: 1483

Answers (1)

Reza
Reza

Reputation: 19903

you can create another pipe for that

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'noComma'
})
export class NoCommaPipe implements PipeTransform {

  transform(val: number): string {
    if (val != null) {
      // here we just remove the commas from value
      return val.toString().replace(/,/g, "");
    } else {
      return "";
    }
  }
}

 <pre>{{i + 1 | number:'3.0-0' | noComma }}&nbsp;{{line}}</pre>

The other solution is having a custom pipe

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'lineNumber'
})
export class LineNumberPipe implements PipeTransform {

  transform(val: number, leadingZeros: number = 2): string {
    if (val != null) {

      return this.pad(val, leadingZeros);
    } else {
      return "";
    }
  }

  private pad(val: number, leadingZeros) {
    const s = val.toString();
    while (s.length < (leadingZeros || 2)) {s = '0' + s;}
    return s;
  }


}


<pre>{{i + 1 | lineNumber:'4' }}&nbsp;{{line}}</pre>

Upvotes: 4

Related Questions