如何使用区域设置获取特定国家/地区的货币符号?

时间:2015-04-30 13:45:23

标签: java locale currency

我已尝试过此代码,但它为某些国家/地区提供Country Code而不是currency symbol

  

我希望货币符号不是代码

数组resourseList包含所有带有代码的国家

String m= (String) Array.get(recourseList,i);
                    String[] ma=m.split(",");
                    Locale locale=new Locale("en", ma[1]);
                    Currency currency= Currency.getInstance(locale);
                    String symbol = currency.getSymbol();
                    ( (TextView) finalV.findViewById(R.id.currencySymbolid)).setText(symbol);

1 个答案:

答案 0 :(得分:12)

它在Currency规范中说:

  

getSymbol()获取默认语言环境的货币符号。   例如,对于美元,如果是默认值,则符号为“$”   locale是美国,而对于其他语言环境,它可能是“US $”。如果不   符号可以确定,返回ISO 4217货币代码。

<强> EDITED 我找到了解决这个问题的方法

import java.util.Currency;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

public class CurrencyCode
{

    public static void main() {
        Map<Currency, Locale> map = getCurrencyLocaleMap();
        String [] countries = { "US", "CA", "MX", "GB", "DE", "PL", "RU", "JP", "CN" };

        for (String countryCode : countries) {
           Locale locale = new Locale("EN",countryCode);
           Currency currency = Currency.getInstance(locale);
           String symbol = currency.getSymbol(map.get(currency));
           System.out.println("For country " + countryCode + ", currency symbol is " + symbol);
        }
    }

    public static Map<Currency, Locale> getCurrencyLocaleMap() {
       Map<Currency, Locale> map = new HashMap<>();
        for (Locale locale : Locale.getAvailableLocales()) {
           try {
             Currency currency = Currency.getInstance(locale);
             map.put(currency, locale);
           }
           catch (Exception e){ 
             // skip strange locale 
           }
        }
        return map;
    }
}

打印:

For country US, currency symbol is $
For country CA, currency symbol is $
For country MX, currency symbol is $
For country GB, currency symbol is £
For country DE, currency symbol is €
For country PL, currency symbol is zł
For country RU, currency symbol is руб.
For country SE, currency symbol is kr
For country JP, currency symbol is ¥
For country CN, currency symbol is ¥