如何在组件中使用货币管道以获取2位小数的值?

6

我有像54781.7622000、1123.11这样的数值。我希望将它们转换为 $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));

我尝试在这个值后面添加额外的参数,例如。

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

但是不起作用。
4个回答

10
您没有向transform()方法传递所有必需的参数。
这是Angular中货币管道transform()方法接受的内容(来源:Angular代码库)。
transform(value: any, currencyCode?: string, display: 'code'|'symbol'|'symbol-narrow'|string|boolean = 'symbol', digitsInfo?: string, locale?: string)

您可以通过像下面这样将正确的数据传递给transform()来解决问题。

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

这里是一个在StackBlitz上的工作示例。你也可以在这个示例中看到如何直接在模板中使用这个管道。


如果值是$100.00,我只想显示$100,怎么办? - swapnil jain
为什么要这样做呢?对于货币来说,最好保留两位小数。如果您仍然想这样做,可以使用this.formatedOutputValue.replace(/.00/g, "") - nash11

5

1
你可以像这样创建管道:

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$/, "");
 }
}

在您的模板中:
 <div>{{data.value | formatedOutputValue}}</div>

如何获取货币符号? - swapnil jain
@swapniljain 你可以使用内置的Angular管道来获取货币符号。 - Alexander Andryichenko

-1

您需要在模板中使用货币管道,如下所示:

{{ outputValue | currency }}

如果未指定货币代码,则默认小数点为2。

Angular在如何正确使用其CurrencyPipe方面有优秀的文档


1
问题是关于在组件中使用这个管道。 - Darren Street

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接