Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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);
like image 272
silverFoxA Avatar asked Apr 30 '15 13:04

silverFoxA


1 Answers

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 ¥
like image 86
MaxZoom Avatar answered Nov 04 '22 05:11

MaxZoom