Convert iso 4217 numeric currency code to currency name
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");
}
source to share
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);
}
source to share
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.
source to share