2

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?

Ricardo Rocha
  • 14,612
  • 20
  • 74
  • 130
  • Does this answer your question? [Angular - Use pipes in services and components](https://stackoverflow.com/questions/35144821/angular-use-pipes-in-services-and-components) – R. Richards Jan 26 '21 at 16:12

2 Answers2

3

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]
})
Ricardo Rocha
  • 14,612
  • 20
  • 74
  • 130
1

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

ColeBear
  • 77
  • 7