Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/33.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何使用货币管道获取组件中最多2位小数的值?_Javascript_Angular_Typescript_Angular8_Angular Pipe - Fatal编程技术网

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

Javascript 如何使用货币管道获取组件中最多2位小数的值?,javascript,angular,typescript,angular8,angular-pipe,Javascript,Angular,Typescript,Angular8,Angular Pipe,我有一个类似于54781.76220001123.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(parseIn

我有一个类似于54781.76220001123.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);

但是不锻炼

可以这样创建管道:

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$/, "");
 }
}
{{ outputValue | currency }}
在模板中:

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

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

这是货币管道
transform()
以角度接受的内容(来源:)

transform(值:any,currencyCode?:字符串,显示:'code'|'symbol'|'symbol-show'|字符串|布尔='symbol',digitsInfo?:字符串,区域设置?:字符串)
您可以通过将正确的数据传递到
transform()
来解决问题,如下所示

this.formattedOutputValue=this.cp.transform(this.outputValue,'USD','symbol','1.2-2');
下面是一个关于的工作示例。在本例中,您还可以看到如何在模板中直接使用管道。

您可以仅使用


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

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$/, "");
 }
}
{{ outputValue | currency }}
如果未指定货币代码,则默认小数点为2


Angular已经开始讨论如何正确使用他们的CurrencyPipe。

如何获取货币符号?@swapniljain您可以使用内置的Angular pipe获取货币符号,如果该值为$100.00,而我只想显示$100,您为什么要为货币执行该操作?最好保留小数点后两位。如果仍要执行此操作,可以使用
this.formattedOutputValue.replace(/.00/g,“”)