11

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?

Taher A. Ghaleb
  • 5,120
  • 5
  • 31
  • 44
Asaf Maoz
  • 675
  • 3
  • 6
  • 23

4 Answers4

12

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");
}
Erwin Bolwidt
  • 30,799
  • 15
  • 56
  • 79
7

With Java 8:

Optional<Currency> currency = Currency.getAvailableCurrencies().stream().filter(c -> c.getNumericCode() == 840).findAny();
Ruben Ernst
  • 335
  • 2
  • 10
Jonathan Rosenne
  • 2,159
  • 17
  • 27
4

A better way to do it:

public class CurrencyHelper {

    private static Map<Integer, Currency> currencies = new HashMap<>();

    static {
        Set<Currency> set = Currency.getAvailableCurrencies();
        for (Currency currency : set) {
             currencies.put(currency.getNumericCode(), currency);
        }
    }

    public static Currency getInstance(Integer code) {
        return currencies.get(code);
    }
}

With a little work the cache can be made more efficient. Please take a look at the source code the Currency class for more information.

Ruben Ernst
  • 335
  • 2
  • 10
Samuel Rowe
  • 152
  • 1
  • 8
0

You have to provide code like "USD" and then it will return Currency object. If you are using JDK 7 then you can use following code. JDk 7 has a method getAvailableCurrencies()

public static Currency getCurrencyByCode(int code) {
    for(Currency currency : Currency.getAvailableCurrencies()) {
        if(currency.getNumericCode() == code) {
            return currency;
        }
    }
    throw new IllegalArgumentException("Unkown currency code: " + code);
}
Zubair Ashraf
  • 279
  • 1
  • 9