Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Number formatting Android 5.0

I've noticed a strange bug while looking at my app on an Android device running 5.0.

On pre 5.0 devices my app will add commas into numbers where necessary. e.g "1,234" or "100,000"

On 5.0 devices the same code displays these numbers as "1234" or "100000". Has any one else noticed this?

I have included my code to format the numbers below - I'm not to sure what needs to change for lollipop devices to show the correct format.

public static String formatNumber(Integer number, String prefix) {
    if (prefix == null) {
        prefix = Constants.PREFIX_SYMBOL;
    }

    StringBuilder stringBuilder = new StringBuilder(prefix);
    NumberFormat numberFormatter = NumberFormat.getIntegerInstance(new Locale("en_UK"));
    stringBuilder.append("").append(numberFormatter.format(number));

    return stringBuilder.toString();
}
like image 771
chuckliddell0 Avatar asked Dec 10 '14 12:12

chuckliddell0


1 Answers

So I think the solution to this is as follows

public static String formatNumber(Integer number, String prefix) {
    if (prefix == null) {
        prefix = Constants.PREFIX_SYMBOL;
    }

    StringBuilder stringBuilder = new StringBuilder(prefix);
    NumberFormat numberFormatter = NumberFormat.getIntegerInstance();
    stringBuilder.append("").append(numberFormatter.format(number));

    return stringBuilder.toString();
}

Removing the Locale from the NumberFormat.getIntegerInstance(); call seems to do the trick. This is added in as some Locales will use non-ASCII decimal digits when formatting integers as specified here. I do not think that this is the case for the regions that my app is available in so it should do the trick.

EDIT:

NumberFormat numberFormatter = NumberFormat.getIntegerInstance(new Locale("en_UK"));

can be replaced with

NumberFormat numberFormatter = NumberFormat.getIntegerInstance(new Locale("en", "GB"));

This will prevent the default locales from using non-ASCII decimal digits.

like image 112
chuckliddell0 Avatar answered Sep 28 '22 04:09

chuckliddell0