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?
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?
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");
}
With Java 8:
Optional<Currency> currency = Currency.getAvailableCurrencies().stream().filter(c -> c.getNumericCode() == 840).findAny();
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.
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);
}