如果数字是字符串格式且字符串中没有小数点,Angular货币管道不会将string/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
恰好
如果您查看您已经应用的regexp: /^(d+)?.((d+)(-(d+))?)?$/
,它需要一个小数点。
下面的正则表达式使小数点可选/^(d+)?.?((d+)(-(d+))?)?$/
如果没有上下文,问题可能不清楚。上一个答案中的管道是在原始数字管道中用于检测字符串中的数字的正则表达式:
const _NUMBER_FORMAT_REGEXP = /^(d+)?.((d+)(-(d+))?)?$/;
为了更接近于模拟原始货币管道的输入条件,可以将管道改为:
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
是从框架内部提取的辅助函数。使用这种方法应该可以很好地工作。