Skip to content
Advertisement

How to create Currency instance with non ISO 3166 country like en_UK?

In my app, I get the user’s default locale using Locale.getDefault() and then pass that to Currency.getInstance(Locale). It mostly works, but I have started getting reports from users which show the following IllegalArgumentException in the stack trace:

Caused by: java.lang.IllegalArgumentException: Unsupported ISO 3166 country: en_UK at java.util.Currency.getInstance(Currency.java:81) at org.

I expected Android to only return valid locales, but that is apparently not the case.

How do I handle such cases to make sure I only get valid ISO 3166 locales? The easy way will be to handle this special case, but I would rather use a generic solution if there is one.

Anyone have experience with this? Thanks.

Advertisement

Answer

The ISO 3166 two-letter abbreviation for the UK is not UK, the correct id is GB. UK is there for compatibility reasons (a mistake made in the past).

I did look for other exeptions but did not find any, so for now i would just handle the special case.

Locale loc = new Locale("en","UK"); // test code

if(loc.getCountry().equals("UK")){
    loc = new Locale(loc.getLanguage(), "GB");
    }
Currency cur = Currency.getInstance(loc);
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement