如果数字是字符串格式且字符串中没有小数点,则Angular currency pipe不会将字符串/ int转换为货币格式。
假设金额为12,我想显示12.00美元,如果通过“12”,则不显示但是如果12.00通过则其正常工作。
//Code
import {Pipe, PipeTransform} from "@angular/core";
import {CurrencyPipe} from "@angular/common";
const _NUMBER_FORMAT_REGEXP = /^(\d+)?\.((\d+)(-(\d+))?)?$/;
@Pipe({name: 'myCurrency'})
export class MyCurrencyPipe implements PipeTransform {
constructor (private _currencyPipe: CurrencyPipe) {}
transform(value: any, currencyCode: string, symbolDisplay: boolean, digits: string): string {
if (typeof value === 'number' || _NUMBER_FORMAT_REGEXP.test(value)) {
return this._currencyPipe.transform(value, currencyCode, symbolDisplay, digits);
} else {
return value;
}
}
}
@Component({
selector: 'my-app',
template: `
<div>
<h2>Hello {{name}}</h2>
<div>{{priceNoDecimal}}</div> {{priceNoDecimal | myCurrency}}
<div>{{priceWithDecimal}}</div> {{priceWithDecimal | myCurrency}}
</div>
`,
})
export class App {
name:string;
priceWithDecimal: string;
priceNoDecimal: string;
constructor() {
this.name = 'Angular2',
this.priceNoDecimal = "12"
this.priceWithDecimal = "12.00"
}
}
@NgModule({
imports: [ BrowserModule ],
declarations: [ App , MyCurrencyPipe],
providers: [CurrencyPipe],
bootstrap: [ App ]
})
export class AppModule {}
//output
Hello Angular2
12
12
12.00
USD12.00
答案 0 :(得分:1)
如果查看已应用的正则表达式:/^(\d+)?\.((\d+)(-(\d+))?)?$/
,则需要小数点。
以下正则表达式使小数点可选/^(\d+)?\.?((\d+)(-(\d+))?)?$/
答案 1 :(得分:1)
如果没有上下文,问题可能不清楚。来自the previous answer的管道是用于检测字符串中数字的正则表达式that is used in original number pipes:
const _NUMBER_FORMAT_REGEXP = /^(\d+)?\.((\d+)(-(\d+))?)?$/;
为了使其密切模仿input conditioning of original currency pipe,管道可能会更改为:
function isNumeric(value: any): boolean {
return !isNaN(value - parseFloat(value));
}
@Pipe({name: 'looseCurrency'})
export class LooseCurrencyPipe implements PipeTransform {
constructor(private _currencyPipe: CurrencyPipe) {}
transform(value: any, currencyCode: string, symbolDisplay: boolean, digits: string): string {
value = typeof value === 'string' && isNumeric(value) ? +value : value;
if (typeof value === 'number') {
return this._currencyPipe.transform(value, currencyCode, symbolDisplay, digits);
} else {
return value;
}
}
}
其中isNumeric
是从framework internals中提取的辅助函数。使用这种方法应该work fine。