How to use the angular decimal pipe in typscript

Viewed 1151

I'm using the angular decimal pipe like this:

// Typescript
@Component({...})
export class ConfusionMatrixComponent {

    @Input()
    roundRules = '1.0-2';
}

// HTML:
<div class="value">{{ getIntensityNumber(i) | number: roundRules }}</div>

How can I use the same pipe but on a typescript function?

2 Answers

I found in a similar question how to use it: just need to import DecimalPipe from @angular/commun and use it as a service:

// Typescript
import { DecimalPipe } from '@angular/common';

@Component({...})
export class ConfusionMatrixComponent {

    @Input()
    roundRules = '1.0-2';

    constructor(private decimalPipe: DecimalPipe) { }

    getRoundNumber(num: number): string | null {
        return this.decimalPipe.transform(num, this.roundRules) ?? '0';
    }

}

// HTML:
<div class="value">{{ getRoundNumber(23.50873) }}</div>

Also, make sure you add the DecimalPipe to your providers angular module:

import { CommonModule, DecimalPipe } from '@angular/common';
@NgModule({
    declarations: [...],
    imports: [CommonModule],
    exports: [...],
    providers: [DecimalPipe]
})

You can use Ng dependency injection.

Make sure to import the module and add DecimalPipe to the providers array.

providers: [DecimalPipe,...]

And then in your component.

import { DecimalPipe } from '@angular/common';

class MyService {
  constructor(private _decimalPipe: DecimalPipe) {}

  transformDecimal(num) {
    return this._decimalPipe.transform(num, '1.2-2');
  }
}

An alternative approach to decimalPipe is formatNumber

Related