convert iso 4217 numeric currency code to currency name

Asaf Maoz picture Asaf Maoz · Nov 4, 2014 · Viewed 7.2k times · Source

I have a an ISO 4217 numeric currency code: 840

I want to get the currency name: USD

I am trying to do this:

 Currency curr1 = Currency.getInstance("840");

But I keep getting

java.lang.IllegalArgumentException

how to fix? any ideas?

Answer

Erwin Bolwidt picture Erwin Bolwidt · Nov 4, 2014

java.util.Currency.getInstance supports only ISO 4217 currency codes, not currency numbers. However, you can retrieve all currencies using the getAvailableCurrencies method, and then search for the one with code 840 by comparing the result of the getNumericCode method.

Like this:

public static Currency getCurrencyInstance(int numericCode) {
    Set<Currency> currencies = Currency.getAvailableCurrencies();
    for (Currency currency : currencies) {
        if (currency.getNumericCode() == numericCode) {
            return currency;
        }
    }
    throw new IllegalArgumentException("Currency with numeric code "  + numericCode + " not found");
}