Java:货币到区域设置映射可能吗?

我有一个存储在数据库中的值与货币金额相关,比如10.0。 我也可以访问Currency / CurrencyCode。 当我不知道Locale时,如何使用NumberFormat / DecimalFormat /(other?)格式化? 根据文档,它将选择一个不适用于外币的默认语言环境。

一般来说,正确的行为是格式化用户首选区域设置中的金额,而不是货币的典型区域设置。 在客户端,您将拥有用户的首选项(Locale.getDefault()); 如果您在Web服务器端执行某些操作,请使用Accept-Language或最好是页面内容的区域设置来获取正确的区域设置。

理由是这样的:英美用户将理解10,000,000欧元.15但不是适合德国的等价物,€10.000.000,15

无论如何,货币本身不包含足以推断合适区域的信息。

JasonTrue是正确的,但您可以覆盖NumberFormat的语言环境的货币:

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

如果货币代码是欧元怎么办? 而且,虽然它遭受了打击,但美元仍然在全世界使用。 从货币代码中推断出区域设置似乎不可靠。 您是否可以为区域设置引入明确的用户首选项?

您要查找的信息不是内置Java货币数据库的一部分,因此没有API。 您可以为许多明确的案例创建自己的表 。

我会说,如果你的数据库存储货币值,它应该同时挂在单位上。 听起来你现在正在这样做。 您可以同时将Locale添加到数据库吗? 可能是一个体面的解决方案

这是一种根据货币代码确定区域设置的方法

 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)