Unexpected currency symbol in currency NumberFormat

445 Views Asked by At

While testing on an Android emulator, I came across an inconsistency between the formatted strings produced by a NumberFormat instance and it's reported currency symbol.

I start by setting up a localized currency formatter like so:

// displayLocale is af_NA
DecimalFormat df = (DecimalFormat) 
NumberFormat.getCurrencyInstance(displayLocale);

// currency is USD
df.setCurrency(currency); // USD localized for af_NA

Then I use it to format a value. The result of invoking:

df.format(1)

is "$1". This might not seem obviously wrong, but when I check the details of the formatter, things dont add up. Invoking:

df.getDecimalFormatSymbols().getCurrencySymbol()

yields "USD" and not the expected "$"...what!? Even stranger, I've yet to find a physical device that I can replicate the issue on. Tests running under Robolectric don't exhibit this behavior either.

Has anybody else come across this behavior before and if so, any idea what's causing it? And finally, is this behavior that might be encountered on physical devices or is it purely an AVD thing?

UPDATE:

Here's a method you can call from any Activity to check for and print out any offending formatters:

void checkFormatters() {
        Currency USD = Currency.getInstance(Locale.US);
        Money oneDollar = new Money(BigDecimal.ONE, USD);

        for(Locale locale : Locale.getAvailableLocales()) {
            DecimalFormat df = (DecimalFormat) NumberFormat.getCurrencyInstance(locale);
            df.setCurrency(USD);
            String currencySymbol = df.getDecimalFormatSymbols().getCurrencySymbol();
            String localizedDollarString = CurrencyUtils.getPrettyCurrencyString(locale, oneDollar);
            if(!localizedDollarString.contains(currencySymbol)) {
                Log.w(TAG, locale.getDisplayName() + ": Expected localized dollar string [" + localizedDollarString +
                        "] to contain currency symbol [" + currencySymbol +
                        "]");
            }
        }
    }

If the device you're testing on has the issue then you'll see results like these:

Uzbek (LATN): Expected localized dollar string [$ 1] to contain currency symbol: [US$]
Uzbek (Uzbekistan,UZ): Expected localized dollar string [$ 1] to contain currency symbol: [US$]
0

There are 0 best solutions below