How to remove trailing zeros from a double

JavaDoubleZeroTrailing

Java Problem Overview


For example I need 5.0 to become 5, or 4.3000 to become 4.3.

Java Solutions


Solution 1 - Java

You should use DecimalFormat("0.#")


For 4.3000

Double price = 4.3000;
DecimalFormat format = new DecimalFormat("0.#");
System.out.println(format.format(price));

output is:

4.3

In case of 5.000 we have

Double price = 5.000;
DecimalFormat format = new DecimalFormat("0.#");
System.out.println(format.format(price));

And the output is:

5

Solution 2 - Java

Use DecimalFormat

  double answer = 5.0;
   DecimalFormat df = new DecimalFormat("###.#");
  System.out.println(df.format(answer));

Solution 3 - Java

Use a DecimalFormat object with a format string of "0.#".

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionWrathView Question on Stackoverflow
Solution 1 - JavaMarcin SzymczakView Answer on Stackoverflow
Solution 2 - JavasoniccoolView Answer on Stackoverflow
Solution 3 - JavadashrbView Answer on Stackoverflow