Java: Currency to Locale Mapping Possible?

2022-09-02 00:36:32

I have a value stored in a DB correlating to a monetary amount, say 10.0. I also have access to the Currency/CurrencyCode. How can I use NumberFormat/DecimalFormat/(other?) to format when I don't know the Locale? According to the docs it will pick a default locale which won't work with a foreign Currency.


答案 1

JasonTrue is correct, but you can override the currency of the NumberFormat's locale:

NumberFormat numberFormat = NumberFormat.getCurrencyInstance(locale);
//the user may have selected a different currency than the default for their locale
Currency currency = Currency.getInstance("GBP");
numberFormat.setCurrency(currency);
numberFormat.format(amount);

答案 2

The correct behavior, generally speaking, is to format the amount in the User's preferred locale, not the currency's typical locale. On the client side, you'll have the user's preference (Locale.getDefault()); if you are doing something on the web server side, use the Accept-Language or, preferably, the page content's locale to obtain the proper a locale.

The reasoning is this: An English-US user will understand € 10,000,000.15 but not the suitable-for-Germany equivalent, € 10.000.000,15

The currency itself doesn't contain enough information to infer a suitable locale, anyway.


推荐