chuckliddell0
chuckliddell0

Reputation: 2061

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();
}

Upvotes: 6

Views: 709

Answers (2)

chuckliddell0
chuckliddell0

Reputation: 2061

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.

Upvotes: 5

Alessandro Roaro
Alessandro Roaro

Reputation: 4733

To group digits you could use DecimalFormat instead of NumberFormat:

DecimalFormat formatter = new DecimalFormat("###,###");

will do the trick.

Upvotes: 0

Related Questions