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:
In Chrome, it seems like toLocaleString()
does not work at all for numbers. Except this approach, I've also tried:
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.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)?
.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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With