How to use DecimalPipe from component in angular?

You can also use formatNumber function (DecimalPipe uses it under the hood). No need for dealing with DI or adding anything to the providers array.


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,...]

Alternatively, as you could see the example on Stackblitz, you can use accounting.

Just simply call by: element.price = format.formatCurrency(element.price);

Once you've define the helper. You could define by: <h2 *ngFor="let item of item">{{ item.price }}</h2> as example.

Component:

import { accounting } from 'accounting';

export function formatCurrency(value) {
    return accounting.formatMoney(value, '', 0, ' ', '.');
}

export function unformatCurrency(value) {
    return accounting.unformat(value);
}

Note: return accounting.formatMoney(value, '', 0, ' ', '.'); You can change ' ' and . with whatever splitter that you want , or space. For how many number behind decimal you could update the 0 number to how many digits you want.