6

I have a values like 54781.7622000 , 1123.11. I want this values in a format like $54781.76 , $1123.11.

//import currency pipe
import { CurrencyPipe } from '@angular/common'

//initialize  in constructor
constructor(private cp: CurrencyPipe)

this.formatedOutputValue = this.cp.transform(parseInt(this.outputValue));

I have tried sum extra parameters after this value like.

this.formatedOutputValue = this.cp.transform(parseInt(this.outputValue),1.2-2);

But doesnt workout.

Tony Ngo
  • 19,166
  • 4
  • 38
  • 60
swapnil jain
  • 252
  • 1
  • 3
  • 22

4 Answers4

10

You are not passing all the needed parameters to the transform()

This is what the currency pipe transform() accepts in Angular (Source: Angular codebase)

transform(value: any, currencyCode?: string, display: 'code'|'symbol'|'symbol-narrow'|string|boolean = 'symbol', digitsInfo?: string, locale?: string)

You can fix your issue by passing the right data to the transform() like below.

this.formatedOutputValue = this.cp.transform(this.outputValue, 'USD', 'symbol', '1.2-2');

Here is a working example on StackBlitz. You can also see how to directly use the pipe in the template in this example.

nash11
  • 8,220
  • 3
  • 19
  • 55
  • and what if the value is suppose $100.00 and i only want to show $100 only – swapnil jain Aug 13 '19 at 10:05
  • Why would you want to do that for currency? It would be better to leave it with 2 decimal places. If you still want to do that you can use ````this.formatedOutputValue.replace(/.00/g, "")````. – nash11 Aug 13 '19 at 10:42
5

you can do it using currency pipe only

this.cp.transform(this.data,'USD','symbol','1.2-2')

Stackblitz

jitender
  • 10,238
  • 1
  • 18
  • 44
1

You can create pipe like this:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
 name: 'formatedOutputValue'
})
export class FormatedOutputValuePipe implements PipeTransform {

 transform(value: any, args?: any): any {
  return value.toFixed(2).replace(/[.,]00$/, "");
 }
}

In your template:

 <div>{{data.value | formatedOutputValue}}</div>
0

You'll want to use the Currency pipe in your template like this:

{{ outputValue | currency }}

The default decimal point is 2 if a currency code is not specified.

Angular has excellent documentation on how to properly use their CurrencyPipe.