我正在尝试根据语言环境获取货币符号。但是,它不是返回符号,而是返回代码。我有一个摘要:
import java.util.Currency; import java.util.Locale; public class CurrencyFormat { public void displayCurrencySymbols() { Currency currency = Currency.getInstance(Locale.US); System.out.println("United States: " + currency.getSymbol()); } public static void main(String[] args) { new CurrencyFormat().displayCurrencySymbols(); } }
对于 Locale.US, 它给出了符号,$但是如果我替换
$
Currency currency = Currency.getInstance(Locale.US);
与
Currency currency = Currency.getInstance(Locale.GERMANY);
然后,用符号代替国家代码。为什么会这样以及如何获取符号?
编辑: 在寻找了一些答案之后,我想清除一下,设置一些特定的默认本地不是解决方案,因为 我需要一次显示所有可用的符号 。
例如
Locale.setDefault(Locale.UK);
会给我欧元符号,但对于美元,它将给出代码,而不是美元符号($)。
您好,请尝试以下代码
import java.text.NumberFormat; import java.util.Comparator; import java.util.Currency; import java.util.Locale; import java.util.SortedMap; import java.util.TreeMap; public class CurrencyExample { public static void main(String[] args) { Utils.getCurrencySymbol( Currency.getInstance(Locale.US).getCurrencyCode()); Utils.getCurrencySymbol(Currency.getInstance(Locale.JAPAN).getCurrencyCode()); Utils.getCurrencySymbol(Currency.getInstance(Locale.UK).getCurrencyCode()); Utils.getCurrencySymbol("INR"); } } class Utils{ public static SortedMap<Currency, Locale> currencyLocaleMap; static { currencyLocaleMap = new TreeMap<Currency, Locale>(new Comparator<Currency>() { public int compare(Currency c1, Currency c2){ return c1.getCurrencyCode().compareTo(c2.getCurrencyCode()); } }); for (Locale locale : Locale.getAvailableLocales()) { try { Currency currency = Currency.getInstance(locale); currencyLocaleMap.put(currency, locale); }catch (Exception e){ } } } public static String getCurrencySymbol(String currencyCode) { Currency currency = Currency.getInstance(currencyCode); System.out.println( currencyCode+ ":-" + currency.getSymbol(currencyLocaleMap.get(currency))); return currency.getSymbol(currencyLocaleMap.get(currency)); } }
上面程序的输出是这样的:
USD:-$ JPY:-¥ GBP:-£ INR:-Rs.