0

When the phone language is Arabic, I get an error on my app:

java.lang.NumberFormatException: For input string: "٣٨.٦٣٤"

When I try to capture the latitude and longitude of a user's location, but when the phone language is in English, I don't get this error.

Here's some code:

this.longitude = Double.parseDouble(UserConfig.getSingleton().getLongitude());
this.latitude = Double.parseDouble(UserConfig.getSingleton().getLatitude());
if (longitude != 0.0 && latitude != 0.0) {
    DecimalFormat formatter = new DecimalFormat("##0.00##");
    UserConfig.getSingleton().setLongitude(formatter.format(longitude));
    UserConfig.getSingleton().setLatitude(formatter.format(latitude)); 
}

I've tried converting latitude and longitude to English fecimal format, and I got this error:

java.lang.NumberFormatException: For input string: "38.634"

I have also tried to make the application language in English, when capturing latitude and longitude to avoid this error, like this:

if (longitude != 0.0 && latitude != 0.0) {
    setDefaultLanguage("en");
    DecimalFormat formatter = new DecimalFormat("##0.00##");
    UserConfig.getSingleton().setLongitude(formatter.format(longitude));
    UserConfig.getSingleton().setLatitude(formatter.format(latitude)); 
}

It worked, but this is not the right solution.

How can I solve this problem?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • 3
    `parseDouble` does not consider the `Locale`, and so is unable to parse Arabic digits – user16320675 Mar 31 '23 at 12:20
  • If you format numbers using a NumberFormat, you should also parse those strings using the same NumberFormat. Do not use Double.parseDouble; use NumberFormat.parse instead. – VGR Mar 31 '23 at 12:20
  • Also, comparing floating point values for equality with `==` / `!=` is dangerous. You want something like `if (Double.compare(longitude, 0.0) > 0 && Double.compare(latitude, 0.0) > 0)` – g00se Mar 31 '23 at 12:35
  • There may also be an issue with the choice of decimal-point character. – Arfur Narf Mar 31 '23 at 12:44
  • 1
    don't create the DecimalFormat, instead use the factory method which takes a Locale - see https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/text/DecimalFormat.html – kleopatra Mar 31 '23 at 13:17
  • *@g00se I think you mixed two problems* I don't think so. Think about the use case. The OP wants to execute the block only if neither latitude nor longitude is zero. We throw out equality and use a comparator-style comparison instead. Now, you might argue that the block could be executed on either being, say, 0.0000000000000001 and *probably* shouldn't be. That would be a better objection ;) Of course, that could be coded for too – g00se Apr 01 '23 at 17:21
  • thank you so much It worked, but I use latitude and longitude to set prayer times. - The error has disappeared, but the prayer times have not been set?! – The Artist For Informatics May 29 '23 at 20:58

0 Answers0