1

How do you round off these longitude and latitude values to 6 decimals each?

p1 contains the longitude and latitude values and "latValue" and "longValue" contain their respective values separately.

p1 = new LatLng((float) (location.getLatitude()),
                    (float) (location.getLongitude()));

float latValue = (float) p1.latitude;
float longValue = (float) p1.longitude;
Lincoln White
  • 639
  • 2
  • 12
  • 29

2 Answers2

2

Since floating point values (ie., float and double) are represented as binary fractions and not as decimal fractions, there really isn't any way to round the value off to any given precision in the stored value.

You can do it when printing the value using String.format("%.6f", p1.latitude)

Arguably, you can use something like the following, but it's going to immediately go back into a float and hence be imprecise again:

round(latValue * 1000000.0) / 1000000.0
David Berry
  • 40,941
  • 12
  • 84
  • 95
  • 1
    What if i make it a double instead of a float? – Lincoln White Mar 17 '16 at 22:43
  • 1
    double's are also floating point numbers, and hence, inherently have no decimal precision. A number as simple as "0.1" cannot be exactly represented in a floating point number of any size. – David Berry Mar 17 '16 at 22:44
  • Basically, the question comes down to you can print/display/convert to a string with any given precision, but the inherent precision won't change. – David Berry Mar 17 '16 at 22:45
0

use DecimalFormat

Example:

float myFloat = 3.123123123f;
DecimalFormat df = new DecimalFormat("#.######");
df.setRoundingMode(RoundingMode.CEILING);

System.out.println(df.format(myFloat));

in your case

System.out.println(df.format(latValue));
System.out.println(df.format(lonValue));
Community
  • 1
  • 1
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
  • Note that this is just DISPLAYING the imprecise floating point number with a resolution of 6 decimals, not actually affecting the precision. – David Berry Mar 17 '16 at 22:41