Detecting number format culture settings

2019-07-21 12:00发布

问题:

I have a webpage that needs to take numeric input, this part is easy enough with some combination of parseFloat, isNaN and (for displaying the values back to the user) toFixed. The problem is that Javascript seems to be completely ignorant of culture here. Some cultures use a decimal comma instead of a decimal point, but Javascript bulks at this.

Supporting the decimal comma isn't too much trouble, I can just replace a comma with a decimal point before parsing the users input and I can do the reverse before displaying the result to the user. My question is, is there a way for Javascript to know the users culture settings? I only care about the decimal separator, so for now I have no interest in other complications like thousands separators or currency.

Is there a reliable (client side) way to detect whether a visitor is using the decimal comma rather than the decimal point?

Update

In case anybody else wants it (or if anybody can see a flaw - other than not working in Chrome, as noted - or a better way), I ended up doing this:

var useComma = (0.1).toLocaleString().indexOf(",") > 0;

Now useComma will be true if the user has comma set as their decimal separator

回答1:

How about

var decimalChar = (0.1).toLocaleString().charAt(1);

Edit, this appears not to work in chrome Internationalization(Number formatting "num.toLocaleString()") not working for chrome



回答2:

I think that trying to detect the user's locale may not actually help that much. If your Web Application is in English language, a user might actually use English-style formatting (e.g. 1.3) even though in their own culture it would be formatted differently (1,3 for fr-FR or es-ES)! And who would blame them?

You could try and be smart and use the solution proposed by Alex K, and/or take into account the accept-language header, the locales matching your localizations (if any) and even GeoIP for a best guess. But to reduce confusion you may want to give your user cues whenever you expect them to enter numerals or dates or other locale-sensitive data.... Display a default value or an example next to the fields, formatted using the same locale as you will be using to parse user input.

If you believe it gives you better user experience to be flexible, you could use a fallback technique and try the formats you expect the most.