How to get the currency symbol for particular country using locale?

折月煮酒 提交于 2020-01-13 09:45:08

问题


I have tried this code and it gives me the Country Codefor some countries instead of the currency symbol

I want the currency symbol not the code

The array resourseList contains all the countries with it's code

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:


It says in the Currency specification:

getSymbol() gets the symbol of this currency for the default locale. For example, for the US Dollar, the symbol is "$" if the default locale is the US, while for other locales it may be "US$". If no symbol can be determined, the ISO 4217 currency code is returned.

EDITED I have found a way around this issue

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

This prints:

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 ¥


来源:https://stackoverflow.com/questions/29969439/how-to-get-the-currency-symbol-for-particular-country-using-locale

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