iGanja
iGanja

Reputation: 2464

Angular decimal pipe to NOT show a leading zero?

Is there a way to use the built-in decimal pipe in Angular and NOT show a leading zero?

I am trying to show baseball batting averages among others that are show as .xxx NOT 0.xxx. The only time a whole number is shown is if the average is equal or over 1.000

Can his be done with the decimal pipe? If not, can someone show a quick way to do this in a custom pipe?

Upvotes: 2

Views: 4858

Answers (2)

Jakub Rybiński
Jakub Rybiński

Reputation: 361

Use another built-in pipe after decimal pipe, slice.

Something like

For

// ts
const score: number = 0.5;

// html

{{ score | number:'1.2-5' }} // output 0.50
{{ score | number:'1.2-5' | slice: 1:4 }}  // output .50
{{ score < 1 ? (score | number:'1.2-5' | slice: 1:4) : (score | number:'1.2-5') }} // output .50 and works for numbers above 1

Upvotes: 2

Martin Parenteau
Martin Parenteau

Reputation: 73721

Here is a custom pipe, derived from DecimalPipe, which removes the leading zero when the value is less than 1.000. By default, it keeps 3 decimal digits:

import { Pipe } from "@angular/core";
import { DecimalPipe } from "@angular/common";

@Pipe({
  name: "battingAvg"
})
export class BattingAvgPipe extends DecimalPipe {
  transform(val: number, digitsInfo: string = "1.3-3", locale?: string) {
    const str = super.transform(val, digitsInfo, locale);
    return str.replace(/^0+([^\d])/, "$1");
  }
}

The pipe is used as follows in the component template:

{{ avg | battingAvg }}
{{ avg | battingAvg: '1.2-5' : 'fr-CA' }}

See this stackblitz for a demo.

Upvotes: 2

Related Questions