如果数字是字符串格式并且字符串中没有小数点,则角度货币管道不会将字符串/整数转换为货币格式。
假设金额为 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