How to use DecimalPipe from component in angular?

Viewed 29808

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?

3 Answers

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

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.

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.

Related