How do I get the currency symbol for a specific country using a locale?
I tried this code and it gives me Country Code
for some countries instead ofcurrency symbol
I want the currency symbol not to be a code
resourseList array contains all countries with 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);
+3
source to share
1 answer
The Currency description states:
getSymbol () gets the symbol of this currency for the default locale. For example, for US dollars, the character is "$" if the default locale is US, while for other places it might be "US $". If no symbol can be specified, the ISO 4217 currency code is returned.
EDITED I found a way to get around this problem
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;
}
}
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 ¥
+7
source to share