Java: Currency to Locale Mapping Possible?

拈花ヽ惹草 提交于 2019-12-18 03:53:28

问题


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:


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.




回答2:


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



回答3:


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.




回答4:


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.




回答5:


Here's a way to determine the locale from the currency code

let locale = NSLocale(localeIdentifier: NSLocale.canonicalLocaleIdentifierFromString(NSLocale.localeIdentifierFromComponents([NSLocaleCurrencyCode: currencyCode])))

let formatter = NSNumberFormatter()
formatter.numberStyle = .CurrencyStyle
formatter.currencyCode = currencyCode
formatter.locale = locale
formatter.maximumFractionDigits = 2
formatter.stringFromNumber(number)


来源:https://stackoverflow.com/questions/758255/java-currency-to-locale-mapping-possible

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!