2017-04-10 48 views
3

如何基于在角2如何基于在用户区域格式化多个角2

实施例的用户区域格式化数目 - 如果用户区域是德国(德国),则号码显示为1.234,56

+1

您可以参考以下链接:http://stackoverflow.com/questions/37684360/how-to-set-locale-for-numbers-in-angular-2-0 –

+0

您是否使用提供的示例?我已经提到这一点。它不工作。 –

回答

0

您可以创建一个过滤器,您可以在显示数字时在整个应用程序中使用该过滤器。

创建过滤器:

angular.module('myApp', []) 
.filter('formatNumber', function() { 
    return function(input) { 
    // Get the locale using any technique 
    var locale = window.navigator.language; 
    if (locale == 'GERMANY') { // test code, replace with your logic 
     return // German formatted number 
    else 
     return // defaults 
    }; 
}) 

角2:

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

@Pipe({name: 'formatNumber'}) 
export class FormatNumberPipe implements PipeTransform { 
    transform(value: string, args: string[]): any { 
    if (!value) return value; 

    // Get the locale using any technique 
    var locale = window.navigator.language; 
    if (locale == 'GERMANY') { // test code, replace with your logic 
     return // German formatted number 
    else 
     return // defaults 
    } 
} 

用法在HTML:

<div> 
    <span class="qty">{{ number | formatNumber }} </span> 
</div> 
+0

我需要在Angular 2中,并且我们不能为所有用户区域设置编写if else。你能帮忙吗? –

+0

@PranjalBakshi您需要为其他语言环境定义一些格式化程序,否则这不能自动执行。我更新了角2的代码。我想只有一些语言环境需要特殊格式化并非全部。 –

3

已经有在JavaScript中能够使用的功能。 你可以称它。 https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString

例子:

var number = 123456.789; 

// German uses comma as decimal separator and period for thousands 
console.log(number.toLocaleString('de-DE')); 
// → 123.456,789 

// Arabic in most Arabic speaking countries uses Eastern Arabic digits 
console.log(number.toLocaleString('ar-EG')); 
// → ١٢٣٤٥٦٫٧٨٩ 

// India uses thousands/lakh/crore separators 
console.log(number.toLocaleString('en-IN')); 
// → 1,23,456.789 

// the nu extension key requests a numbering system, e.g. Chinese decimal 
console.log(number.toLocaleString('zh-Hans-CN-u-nu-hanidec')); 
// → 一二三,四五六.七八九 

// when requesting a language that may not be supported, such as 
// Balinese, include a fallback language, in this case Indonesian 
console.log(number.toLocaleString(['ban', 'id'])); 
// → 123.456,789 

你可以只此语言环境存储在它周围的一些常数文件&发挥。

+0

但我要如何阅读用户区域设置呢? –

+0

你可以使用'navigator.language' –