shkschneider
shkschneider

Reputation: 18253

Android location to string issue

Here is the code I use the put locations to strings:

public static String locationStringFromLocation(final Location location) {
    return String.format("%.3f %.3f", location.getLatitude(), location.getLongitude());
}

And from some other devices, from time to time I get: -7.2900002123788E-4 7.270000060088933E-4 as location string and not -7.290 7.270 for example.

Edit

Updated code. Will this fix the issue?

DecimalFormat decimalFormat = new DecimalFormat("#.###");
if (location != null) {
    final String latitude = decimalFormat.format(Float.valueOf(Location.convert(location.getLatitude(), Location.FORMAT_DEGREES)));
    final String longitude = decimalFormat.format(Float.valueOf(Location.convert(location.getLongitude(), Location.FORMAT_DEGREES)));
    return latitude + " " + longitude;
}
return decimalFormat.format(0.0F) + " " + decimalFormat.format(0.0F);

Upvotes: 3

Views: 9419

Answers (2)

hieudev develo
hieudev develo

Reputation: 53

one line, one method, convinient workaround:

String.substring(beginIndex,finalIndex)

so in your case:

latInDecimal = lat.substring(0,5)
lngInDecimal = lng.substring(0,5)

Upvotes: 0

Tudor Luca
Tudor Luca

Reputation: 6419

You can use public static String convert (double coordinate, int outputType) from Location Class. The outputType can be one of FORMAT_DEGREES, FORMAT_MINUTES, or FORMAT_SECONDS.

public static String locationStringFromLocation(final Location location) {
    return Location.convert(location.getLatitude(), Location.FORMAT_DEGREES) + " " + Location.convert(location.getLongitude(), Location.FORMAT_DEGREES);
}

Upvotes: 5

Related Questions