How to use DecimalPipe from component in angular?

Soumya Gangamwar picture Soumya Gangamwar · Dec 17, 2018 · Viewed 13.3k times · Source

I have a requirement that I have to convert the number using the decimal pipe from ts

Instead of use decimal pipe like this

<td>{{rmanFmvRulesDef.max  | number :'1.2-2'}}</td>

I want to manipulate it from the component, can anyone please help me?

Answer

parag badala picture parag badala · Dec 17, 2018

As usual in angular you can rely on DI. You can override the transform function in the ts.

import { DecimalPipe } from '@angular/common';
class MyService {
  constructor(private _decimalPipe: DecimalPipe) {
}
transformDecimal(num) {
    return this._decimalPipe.transform(num, '1.2-2');
   }
}

Add DecimalPipe in the providers Array otherwise it will give an error

providers: [DecimalPipe,...]