Reputation: 655
Why do numbers read from database or file downloaded to phone become Persian numbers when the language is Farsi? Is there a general solution to this problem?
error :
Fatal Exception: java.lang.NumberFormatException
For input string: "۶٫۸۱"
in this line :
float twoDigitsF = Float.valueOf(decimalFormat.format(distanceInMeters));
my function is :
public static float CalculationByDistance(double start_lat, double start_lng, double end_lat, double end_lng) {
Location loc1 = new Location("");
loc1.setLatitude(start_lat);
loc1.setLongitude(start_lng);
Location loc2 = new Location("");
loc2.setLatitude(end_lat);
loc2.setLongitude(end_lng);
float distanceInMeters = loc1.distanceTo(loc2);
DecimalFormat decimalFormat = new DecimalFormat("#.##");
float twoDigitsF = Float.valueOf(decimalFormat.format(distanceInMeters));
return twoDigitsF;
}
the log of distanceInMeters in console is : 6.8146
Upvotes: 1
Views: 107
Reputation: 5608
Since your log is printed in English digits, it shows that the culprit is laying behind the DecimalFormat
no-args constructor which uses the your default app locale as the decimal format locale. In your case you just need to declare your locale preference which is Locale.ENGLISH
to your DecimalFormat
constructor so it would be:
DecimalFormat.getInstance(Locale.ENGLISH).format(distanceInMeters);
Note that DecimalFormat.getInstance()
returns a NumberFormat
instance which does not give you the ability to use your own pattern. Judging by your logged distance and your pattern I can say you're looking for a rounding procedure to reduce your distance floating points by 2. In that case you don't need to convert your number to formatted String and the parsing it back to float which is heavy of course; you just need to use round(float)
method from Math
class with some trick:
float twoDigitsF = Math.round(distanceInMeters * 100) / 100f;
Hope it helps.
Upvotes: 2
Reputation: 1992
you can use this method to change number format :
private static float getUSNumber(String Numtoconvert){
NumberFormat formatter = NumberFormat.getInstance(Locale.US);
try {
if(Numtoconvert.contains("٫"))
Numtoconvert=formatter.parse(Numtoconvert.split("٫")[0].trim())+"."+formatter.parse(Numtoconvert.split("٫")[1].trim());
else
Numtoconvert=formatter.parse(Numtoconvert).toString();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return Float.valueOf(Numtoconvert);
}
and then :
CalculationByDistance(getUSNumber(start_lat), getUSNumber(start_lng), getUSNumber(end_lat), getUSNumber(end_lng));
although I think you don't need them and you get number from wrong place!
Upvotes: 0