对我来说最好的选择是著名的https://www.npmjs.com/package/numeral 包。 (他使用与moment.js 相同的逻辑)
要安装它:npm i numeral@2.0.6 和类型 npm i --save-dev @types/numeral@0.0.22
在您的ts 文件中,您可以按如下方式使用:
`R$ ${numeral(<your-model-value>).value().toLocaleString()}`
对于 HTML 模板,您可以像这样创建 Pipe:
import {Pipe, PipeTransform} from '@angular/core';
import * as numeral from 'numeral';
@Pipe({
name: 'numberLocale'
})
export class NumberLocalePipe implements PipeTransform {
transform(value: any, args?: any): any {
const numeralNumber = numeral(value);
return numeralNumber.value().toLocaleString();
}
}
此外,对于 currency(和语言环境),一个好的策略是使用包 ng2-currency-mask 用于货币 HTML 中的掩码(但对于 ts 文件,您可能应该在保存你的模型对象之前用numeral“翻译”模型中的绑定值。
在 HTML 模板上使用 ng2-currency-mask:
<input [(ngModel)]="model.value"
[options]="{ prefix: 'R$ ', thousands: '.', decimal: ',' }"
allowNegative="false" currencyMask>
在ts 之前保存模型:
if(this.model.value)
this.model.value = numeral(this.model.value).value();
https://github.com/cesarrew/ng2-currency-mask