How to set the locale for numbers in angular 2.0

The format of the number in Swiss German is similar to "100,000.00" (not "100,000.00"). How can i change this? I tried changing the settings in number_pipe.js from en-US to de-CH without success.

var defaultLocale: string = 'de-CH'; 

Is there a workaround or should I implement my own channel?

+2
numbers angular locale angular2-pipe
source share
4 answers

Try using locale-number .pipe.ts or

you can create a simple channel based on NumeralJs to format numbers

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

+2
source share

If you need only one locale for your application, you can currently (@ angular ~ 2.4.0) register the locale provider with @NgModule.

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

The following is my decision and this will help someone.

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

In html you can use the following

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

The format of the number will change according to the language value.

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat for details.

+2
source share

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

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

In your ts file you can use the following:

 `R$ ${numeral(<your-model-value>).value().toLocaleString()}` 

For an HTML template, you can create a Pipe as follows:

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

In addition, for currency (and locales), a good strategy is to use the ng2-currency-mask package for macros in HTML (but in ts files that may need to "translate" the anchored value in the model using numeral before saving the model object.

Using ng2-currency-mask in an HTML template:

 <input [(ngModel)]="model.value" [options]="{ prefix: 'R$ ', thousands: '.', decimal: ',' }" allowNegative="false" currencyMask> 

And on ts before saving the model:

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

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

0
source share

All Articles