How to format numbers and dates based on user loca

2019-06-17 15:37发布

I need a way to automatically format Date and Number objects based on locale settings of my users.

So far, I've been using toLocaleString() function for dates. For numbers, toLocaleString() is also available, but as you can see in the jsFiddle I've prepared, results vary greatly between browsers. With English (United States) locale on my Windows machine, I get this:

  • IE9: 15,000.00
  • Firefox: 15,000
  • Chrome: 15000

In Chrome, it seems like toLocaleString() does not work at all for numbers. Except this approach, I've also tried:

  • To use MicrosoftAjax.js library localeFormat() function, but no matter which locale I've set on my PC (by using "Region and Language" dialog), dates and numbers were still both formated in US format.
  • To use libraries like Globalize. Although they do offer formatting capabilities, they are not able to detect user's locale automatically.

So, to summarize: how to automatically format numbers and dates to respect regional settings of user that browses the webpage in a way that works in all major browsers (IE, Firefox, Chrome)?

2条回答
冷血范
2楼-- · 2019-06-17 16:21

Today the Internationalization API @Jon mentioned is widely supported. From a primitive number you can use Number(123456).toLocaleString() and Chrome now returns "123,456" as expected (for a US locale). I haven't tested on IE11/Edge but support is there according to caniuse.

查看更多
聊天终结者
3楼-- · 2019-06-17 16:29

.toLocaleString() functions on native Javascript objects is practically useless because it does not let you specify the locale or otherwise control their behavior.

Until the ECMAScript i18n API becomes a reality (which is probably too far in the future to be worth considering at all right now) your only practical option is using libraries such as Globalize, but then as you say you need to detect the user's preferred locale.

Detecting the locale is another problem that is not easily solved with pure Javascript. Specifically, the Accept-Language header is IMHO practically useless as a means of locale detection because it is not visible to the vast majority of web users. That's why web applications typically provide a custom mechanism for the user to select a locale which is communicated back to the server, and the server uses this information to configure each response thereafter.

查看更多
登录 后发表回答