如何根据 angular 2 中的用户区域设置格式化数字

Yel*_*nda 5 angular2-services angular

如何根据 angular 2 中的用户区域设置格式化数字

示例 - 如果用户语言环境为德语(德国),则数字显示为 1.234,56

小智 6

There already is a function available in JavaScript. You can just call it. https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString

Example :

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
Run Code Online (Sandbox Code Playgroud)

You can just store this locale's in some constant file & play around it.


Ham*_*aig 1

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

创建过滤器:

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
  };
})
Run Code Online (Sandbox Code Playgroud)

角度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
  }
}
Run Code Online (Sandbox Code Playgroud)

HTML 中的用法:

<div>
    <span class="qty">{{ number | formatNumber }} </span>
</div>
Run Code Online (Sandbox Code Playgroud)