gpt4 book ai didi

java - 没有获取特定语言环境的货币符号

转载 作者:IT老高 更新时间:2023-10-28 20:44:32 27 4
gpt4 key购买 nike

我正在尝试根据语言环境获取货币符号。但不是返回符号,而是返回代码。我有一个片段:

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

会给我欧元符号,但对于doller,它将给出代码而不是doller符号($)。

最佳答案

您好,请尝试以下代码

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.

关于java - 没有获取特定语言环境的货币符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15106484/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com