Java: Currency to Locale Mapping Possible?

后端 未结 4 1198
Happy的楠姐
Happy的楠姐 2020-12-16 12:11

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?)

相关标签:
4条回答
  • 2020-12-16 12:56

    I would say that if your database is storing a currency value it should be hanging onto the units at the same time. It sounds like you're doing that now. Can you add the Locale to the database at the same time? Could be a decent solution.

    0 讨论(0)
  • 2020-12-16 13:00

    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);
    
    0 讨论(0)
  • 2020-12-16 13:09

    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.

    0 讨论(0)
  • 2020-12-16 13:14

    What if the currency code is EUR? And, while it has taken a beating, USD is still used throughout the world. Inferring the locale from the currency code seems unreliable. Can you introduce an explicit user preference for the locale instead?

    The information you are looking for is not part of the built-in Java currency database, so there is not an API for it. You could create your own table for the many cases that are unambiguous.

    0 讨论(0)
提交回复
热议问题