【问题标题】:How to set locale for numbers in angular 2.0如何为 Angular 2.0 中的数字设置语言环境
【发布时间】:2016-10-07 15:37:24
【问题描述】:

瑞士德语中的数字格式类似于“100'000.00”(不是“100,000.00”)。我该如何改变呢?我尝试将 number_pipe.js 中的设置从 en-US 更改为 de-CH,但没有成功。

var defaultLocale: string = 'de-CH';

有解决方法还是我必须实现自己的管道?

【问题讨论】:

  • 你可以看到我的回答here

标签: angular numbers locale angular2-pipe


【解决方案1】:

如果您的应用只需要一种语言环境,您现在可以(@angular ~2.4.0)在@NgModule 中注册语言环境提供程序。

@NgModule({
    ...
    providers: [
        {provide: LOCALE_ID, useValue: "de-CH"}
    ]
})
export class AppModule {}

【讨论】:

  • 你必须添加: import { LOCALE_ID } from '@angular/core';
  • 你可能必须在 Angular 中使用内置的DecimalPipe,例如。 {{myNumberVar|number:'1.0-2'}} 查看文档 (angular.io/api/common/DecimalPipe)
【解决方案2】:

以下是我的解决方案,它会对某人有所帮助。

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'amountConverter'
})
export class AmountConverterPipe implements PipeTransform {

  transform(value: number | string, locale?: string): string {
    return new Intl.NumberFormat(locale, {
      minimumFractionDigits: 2
    }).format(Number(value));
  }

}

在html中可以如下使用

 <span class="strong">{{Price  | amountConverter:locale}}</span>

数字格式将根据语言环境的值而改变。

详情请参考https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat

【讨论】:

    【解决方案3】:

    尝试使用locale-number.pipe.ts

    你可以创建一个基于 NumeralJs 的简单管道来格式化数字

    https://github.com/adamwdraper/Numeral-js

    【讨论】:

      【解决方案4】:

      对我来说最好的选择是著名的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

      【讨论】:

        猜你喜欢
        • 2017-05-25
        • 1970-01-01
        • 1970-01-01
        • 2016-04-26
        • 1970-01-01
        • 2021-12-02
        • 1970-01-01
        • 2019-08-27
        • 2019-08-27
        相关资源
        最近更新 更多