How to set locale for numbers in angular 2.0

后端 未结 4 2112
走了就别回头了
走了就别回头了 2020-12-11 02:37

The number format in Swiss German is like \"100\'000.00\" (not \"100,000.00\"). How can I change that? I tried to change the settings in number_pipe.js from en-US to de-CH w

4条回答
  •  渐次进展
    2020-12-11 03:40

    The best option for me was the famous https://www.npmjs.com/package/numeral package. (he works with same logical of the moment.js)

    To install it: npm i numeral@2.0.6 and with types npm i --save-dev @types/numeral@0.0.22

    At your ts file you can use as follow:

    `R$ ${numeral().value().toLocaleString()}`
    

    For HTML template you can create a Pipe like this:

    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();
      }
    }
    

    Additionally, for currency (and locales) a good strategy is use the package ng2-currency-mask for currency masks in HTML (but on ts files you may should "translate" the binded value in the model with numeral before save your model object.

    Using ng2-currency-mask on HTML Template:

    
    

    And on ts before save the model:

    if(this.model.value)
       this.model.value = numeral(this.model.value).value();
    

    https://github.com/cesarrew/ng2-currency-mask

提交回复
热议问题