将 API 中的数字格式化为 Angular
Format the number from API in Angular
我从 ASP.NET Core API 得到 Km 范围,并且想用 1000 分隔符格式化数字,例如:
75,000 - 100,000 - 125,000 等等。
我如何通过以下方式实现此目的:
JSON 输出:
[
{
"Id": 8,
"Km": 75000
},
{
"Id": 9,
"Km": 100000
},
{
"Id": 10,
"Km": 125000
},
{
"Id": 11,
"Km": 150000
}
]
我的 KM 模型
export class KmRange {
Id: number;
Km: number;
}
我的组件:
dropdownList = [];
this.dropdownList = await this._service.getKmRanges().toPromise();
编辑 - 我现在就是这样使用的
I cam accross this post
它说正则表达式比 toLocaleString 快,所以我最终像这样使用。
this.dropdownList = await this._service.getKmRanges().toPromise();
for (var i = 0; i < this.dropdownList.length; i++) {
this.dropdownList[i].Km = this.toCommas(this.dropdownList[i].Km);
}
toCommas(value) {
return value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
您可以使用 Number.prototype.toLocaleString 和 'en-US' 选项。
result: string[] = dropdownList.map(x => x.toLocaleString('en-US'));
您可以在 API 和 Angular 中使用区域设置设置数字(或日期)的格式。
最好让 Angular 处理本地化,因为它是 运行 在客户端,我们不需要为 API 投入更多工作。
您可以按照此设置语言环境 https://angular.io/guide/i18n
并以此为例来格式化数字 https://angular.io/api/common/DecimalPipe
更新:
您可以使用此处列出的模板 (https://cuppalabs.github.io/angular2-multiselect-dropdown/#/templating)
<c-item>
<ng-template let-item="item">
<label>{{item.Km | number:1.0-3:'en-US'}}</label>
</ng-template>
</c-item>
我从 ASP.NET Core API 得到 Km 范围,并且想用 1000 分隔符格式化数字,例如: 75,000 - 100,000 - 125,000 等等。 我如何通过以下方式实现此目的:
JSON 输出:
[
{
"Id": 8,
"Km": 75000
},
{
"Id": 9,
"Km": 100000
},
{
"Id": 10,
"Km": 125000
},
{
"Id": 11,
"Km": 150000
}
]
我的 KM 模型
export class KmRange {
Id: number;
Km: number;
}
我的组件:
dropdownList = [];
this.dropdownList = await this._service.getKmRanges().toPromise();
编辑 - 我现在就是这样使用的
I cam accross this post
它说正则表达式比 toLocaleString 快,所以我最终像这样使用。
this.dropdownList = await this._service.getKmRanges().toPromise();
for (var i = 0; i < this.dropdownList.length; i++) {
this.dropdownList[i].Km = this.toCommas(this.dropdownList[i].Km);
}
toCommas(value) {
return value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
您可以使用 Number.prototype.toLocaleString 和 'en-US' 选项。
result: string[] = dropdownList.map(x => x.toLocaleString('en-US'));
您可以在 API 和 Angular 中使用区域设置设置数字(或日期)的格式。
最好让 Angular 处理本地化,因为它是 运行 在客户端,我们不需要为 API 投入更多工作。
您可以按照此设置语言环境 https://angular.io/guide/i18n
并以此为例来格式化数字 https://angular.io/api/common/DecimalPipe
更新:
您可以使用此处列出的模板 (https://cuppalabs.github.io/angular2-multiselect-dropdown/#/templating)
<c-item>
<ng-template let-item="item">
<label>{{item.Km | number:1.0-3:'en-US'}}</label>
</ng-template>
</c-item>