最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to use currency pipe to get values upto 2 decimal digits in component? - Stack Overflow

programmeradmin4浏览0评论

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.

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.

Share Improve this question edited Aug 13, 2019 at 9:35 Tony 20.1k6 gold badges41 silver badges62 bronze badges asked Aug 13, 2019 at 9:31 swapnil jainswapnil jain 2621 gold badge3 silver badges22 bronze badges
Add a comment  | 

4 Answers 4

Reset to default 12

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.

you can do it using currency pipe only

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

Stackblitz

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>

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.

发布评论

评论列表(0)

  1. 暂无评论