Android 5.0 number formatting

I noticed a strange error while looking at my application on an Android device with 5.0.

On devices with preinstalled 5.0, my application will add commas to numbers where necessary. for example, "1,234" or "100,000"

On 5.0 devices, the same code displays these numbers as β€œ1234” or β€œ100000”. Has anyone else noticed this?

I have included my code for formatting the numbers below - I'm not sure what needs to be changed for devices with lollipop 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(); } 
+5
source share
2 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 Locale from a call to NumberFormat.getIntegerInstance(); seems to be doing the trick. This is added because some Locales will use non-ASCII decimal numbers when formatting integers, as indicated here . I do not think that this applies to the regions in which my application is available, so it should do the trick.

EDIT:

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

can be replaced by

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

This will prevent locals from using default decimal digits without ASCII.

+5
source

To group numbers, you can use DecimalFormat instead of NumberFormat :

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

will do the trick.

0
source

Source: https://habr.com/ru/post/1208729/


All Articles