如何根据角度2中的用户区域设置格式化数字
示例 - 如果用户区域设置是德语(德国),则该号码显示为1.234,56
答案 0 :(得分:4)
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
您只需将此区域设置存储在某个常量文件中即可。玩弄它。
答案 1 :(得分: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
};
})
Angular 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>