DecimalFormat force latin numbers when users have different locales

1.1k views Asked by At

I am trying to parse a float while using a DecimalFormat twoDForm to reduce the number of decimals. To set the number of decimals I have instantiated as following:

twoDForm  = new DecimalFormat("#.##");

Then to parse the float I do call the following:

Float.valueOf(twoDForm.format(cameraPosition.x)

which in some cases seemingly based on locale throws

NumberFormatException: Invalid float: "١٥.٨٦" non latin numbers or font

I have been getting several different issues with NumberFormatException because of locales and differences in how Android devices are handling numbers and symbols, so I have also added the following to the DecimalFormat:

DecimalFormatSymbols dfs = new DecimalFormatSymbols();
dfs.setDecimalSeparator('.');
dfs.setMinusSign('-');
twoDForm.setDecimalFormatSymbols(dfs);

I've been able to solve the ones that involve some cases using different kinds of commas, and minus sign, but now I'm faced with this: java.lang.NumberFormatException: Invalid float: "١٥.٨٦"

When I google it I find arabic book suggestions so I'm guessing it's some other way of handling numbers for different languages. Is there any way to force that to use "regular" numbers to avoid that, which would allow me to simply call the same Float.valueOf(...) without having to add specific locales for each possible case?

Thanks!

2

There are 2 answers

7
Dawood ibn Kareem On BEST ANSWER

The characters in that String are the Arabic digits for 1, 5, 8 and 6. You'll need an Arabic-speaking locale to be able to parse them.

The following code works for me, and prints 15.86 as required.

Locale saudiArabia = new Locale("ar", "SA");
NumberFormat arabicFormat = NumberFormat.getInstance(saudiArabia);
try {
    Number parsed = arabicFormat.parse("١٥.٨٦");
    System.out.println(parsed);
} catch (ParseException e) {
    e.printStackTrace();
}
0
Ana-Maria B On

The problem there is from the fact that the device language is arabis. If so, automatically DecimalFormatSymbols will convert the latin numbers in arabic numbers. The best approach and the easiest on is to set the locale directly :

final DecimalFormatSymbols decimalSymbol = new DecimalFormatSymbols(Locale.US);