-2

I'm using DecimalFormat to round my numbers to exactly with one decimal. However, numbers like 20 don't show up as 20.0 and it just shows 20.

So my code is like this:

int myWholeNumber = 20;
DecimalFormat df = new DecimalFormat("#.#");
double toDouble = Double.parseDouble(df.format(myWholeNumber));
System.out.println(toDouble);

but the output differs from the wanted one:

Output

20

Wanted

20.0
Khayyam
  • 509
  • 3
  • 17
  • Does this answer your question? [How to print a float with 2 decimal places in Java?](https://stackoverflow.com/questions/2538787/how-to-print-a-float-with-2-decimal-places-in-java) – OH GOD SPIDERS Oct 21 '20 at 13:25
  • @OHGODSPIDERS no it was't – Khayyam Oct 21 '20 at 13:26
  • It's hard to believe you searched "a lot" since simply reading [the docs](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/text/DecimalFormat.html) would have answered your question. (Hint: `#` is defined as "Digit, zero shows as ***absent***".) – David Conrad Oct 21 '20 at 13:54
  • @DavidConrad thnx David my mistake is i searched just in **Stackoverflow** not other sites, any way it was really helpful – Khayyam Oct 21 '20 at 14:14
  • It's a good idea to always start with the documentation for the classes you're using. – David Conrad Oct 21 '20 at 20:01

1 Answers1

4

Explicitly have a zero in your format string:

import java.text.DecimalFormat;

public class Main {

    public static void main(String[] args) {
        int myWholeNumber = 20;
        DecimalFormat df = new DecimalFormat("#.0");
        double myDoubleNumber = Double.valueOf(myWholeNumber);
        System.out.println(df.format(myDoubleNumber));
    }

}

Output:

20.0

Try it out here.

Sash Sinha
  • 11,515
  • 3
  • 18
  • 35