Pregunta

I want to display GPS coordinates upto just 6 decimal places. e.g. if my GPS location is something like x.yyyyyyyyyy I want to display just x.yyyyyy and for this I use DecimalFormat class. But, if the number is like 8.3456709012, the output for the following code is like 8.34568

_yPos = 8.3456709012;
DecimalFormat decimalFormat = new DecimalFormat("#.######");
String yCoord = decimalFormat.format(_yPos);

whereas the expected output is 8.345670. Can anybody show me a way to do this?

¿Fue útil?

Solución

Use "0.000000" as the formatting code.

The character # is for "Digit, zero shows as absent": http://docs.oracle.com/javase/6/docs/api/java/text/DecimalFormat.html

Also, you have to set the rounding mode to DOWN if you really want the output 8.345670 rather than 8.345671:

DecimalFormat decimalFormat = new DecimalFormat("0.000000");
decimalFormat.setRoundingMode(java.math.RoundingMode.DOWN);

Otros consejos

Joni Salonen's answer suggests how you can preserve trailing zeros, but the coordinates will still be half rounded as the default rounding mode is RoundingMode.HALF_EVEN.

You can set the rounding mode by using

decimalFormat.setRoundingMode(RoundingMode.DOWN);

This method is available since 1.6

Refer http://docs.oracle.com/javase/6/docs/api/java/text/DecimalFormat.html#setRoundingMode%28java.math.RoundingMode%29

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top