Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use DecimalPipe from component in angular?

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?

like image 855
Soumya Gangamwar Avatar asked Dec 17 '18 07:12

Soumya Gangamwar


People also ask

What function does DecimalPipe do?

DecimalPipelink. Formats a value according to digit options and locale rules. Locale determines group sizing and separator, decimal point character, and other locale-specific configurations.

What is the default value of maxFractionDigits while using the DecimalPipe?

Default is 0. maxFractionDigits: The maximum number of digits after the decimal point. Default is 3.

How do you use custom pipes?

Steps Involved In Creating a Custom Pipe In Angular are: 1) Create a Pipe Class and decorate it with the decorator @Pipe. 2) Supply a name property to be used as template code name. 3) Register your Pipe in the module under declarations. 4) Finally, implement PipeTransform and write transformation logic.


2 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,...]
like image 74
parag badala Avatar answered Oct 20 '22 09:10

parag badala


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.

like image 6
Wildhammer Avatar answered Oct 20 '22 08:10

Wildhammer