Convert iso 4217 numeric currency code to currency name

I have an ISO 4217 numeric currency code: 840

I want to get the name of the currency: USD

I am trying to do this:

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

      

But I keep getting

java.lang.IllegalArgumentException

how to fix? any ideas?

+5


source to share


4 answers


java.util.Currency.getInstance

only supports ISO 4217 currency codes rather than currency numbers. However, you can get all currencies using the method getAvailableCurrencies

and then search for the code with code 840 by comparing the result of the method getNumericCode

.

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

      

+7


source


As of Java 8:



Optional<Currency> currency = Currency.getAvailableCurrencies().stream().filter(c -> c.getNumericCode() == 840).findAny();

      

+1


source


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

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

      

0


source


The best way to do it:

public class CurrencyHelper {

    private static Map<Integer, Map> 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 effort, you can make your cache more efficient. Please take a look at the source code for the Currency class for more information.

0


source







All Articles