【问题标题】:Format the number from API in Angular在 Angular 中格式化来自 API 的数字
【发布时间】:2020-03-10 17:52:01
【问题描述】:

我从 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
    }
]

我的知识管理模型

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, ",");
}

【问题讨论】:

    标签: typescript asp.net-core angular9


    【解决方案1】:

    您可以在 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>
    

    【讨论】:

    • 我很困惑..在提到的示例链接中,它们在 ngmodel 中发生了变化,但在我的情况下,我需要更改数组 (dropdownList[])。我该怎么做。
    • 如何在 html 中使用你的下拉列表?
    • 我更新了答案。我不确定你想要什么语言环境,有多少个十进制数字。我只是举个例子。
    【解决方案2】:

    您可以将Number.prototype.toLocaleString 与“en-US”选项一起使用。

    result: string[] = dropdownList.map(x => x.toLocaleString('en-US'));
    

    【讨论】:

    • this.dropdownList = await (await this._service.getKmRanges().toPromise()).map(x => x.Km.toLocaleString("en-US")); // 不工作!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多