-2

Hi how i can to get a decimal with place?, for example 9.924kms by 9.9kms

My code is

td = String.valueOf(totalDistance / 1000.0);
Camilo
  • 1
  • 4

2 Answers2

1

You can try this,

 DecimalFormat format= new DecimalFormat("#.0");
 td = format.format(totalDistance / 1000.0);

Or refer this answer which is for rounding numbers.

Jyoti JK
  • 2,141
  • 1
  • 17
  • 40
0

Use DecimalFormat. You can also set RoundingMode to get the ceiling for last digit . Below is an example .

 double x=2.7883;
 DecimalFormat df = new DecimalFormat("#.0");
 System.out.println(df.format(x));

Output:- 2.8

For setting mode you can use .

 df.setRoundingMode(RoundingMode.FLOOR);
ADM
  • 20,406
  • 11
  • 52
  • 83
  • Beware of `.#`, [it won't print the decimal number if it'll be 0](https://ideone.com/Ka5JvF)... you need `.0` to always have one decimal number (more on http://www.baeldung.com/java-decimalformat) – Andrea Ligios Feb 28 '18 at 17:29
  • 1
    Thanks for clarifying – ADM Feb 28 '18 at 17:48