首页 > 解决方案 > 如何使用货币管道在组件中获取最多 2 位十进制数字的值?

问题描述

我有一个像 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);

但不锻炼。

标签: javascriptangulartypescriptangular8angular-pipe

解决方案


您没有将所有需要的参数传递给transform()

这是货币管道transform()在 Angular 中接受的内容(来源: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上的一个工作示例。您还可以在此示例中看到如何直接使用模板中的管道。


推荐阅读