76

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

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Wrath
  • 825
  • 1
  • 6
  • 6
  • 11
    Note: Unlike the top answer in the linked question, all of these answers rely on an expected input of only one decimal place. Everything longer than one decimal place will be rounded, which may not be desired behaviour. – tommoyang Jun 04 '14 at 02:07
  • 1
    This is ugly as hell but it works: String.format(doubleVal).replaceAll("\\.0+$", ""); – mvmn Jan 18 '19 at 15:55
  • 4
    P.S. Ended up using this: DecimalFormat("#.################").format(doubleVal); // This ensures no trailing zeroes and no separator if fraction part is 0 (there's a special method setDecimalSeparatorAlwaysShown(false) for that, but it seems to be already disabled by default). But will produce up to 16 digits of fractional part (and you can put more # there if you think 16 is not enough). – mvmn Jan 20 '19 at 12:38

3 Answers3

110

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
angelatlarge
  • 4,086
  • 2
  • 19
  • 36
Marcin Szymczak
  • 11,199
  • 5
  • 55
  • 63
7

Use DecimalFormat

  double answer = 5.0;
   DecimalFormat df = new DecimalFormat("###.#");
  System.out.println(df.format(answer));
Jay
  • 37
  • 8
soniccool
  • 5,790
  • 22
  • 60
  • 98
1

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

dashrb
  • 952
  • 4
  • 10
  • 17
    this fails in the case of 4.32 which becomes 4.3 – narancs Mar 31 '16 at 12:50
  • 1
    fair point, although the OP didn't indicate how many places were desired. I can't think of a good reason to truncate trailing 0's but keep non-zeros as far as they are printable. IMHO, when printing a double, the code should specify the desired number of digits of precision (the number of #'s after the period). – dashrb Apr 13 '16 at 13:59
  • 1
    @Karoly DecimalFormat df = new DecimalFormat("###.##"); df.setRoundingMode(RoundingMode.HALF_UP); System.err.println(df.format(4.325)); System.err.println(df.format(4.30)); System.err.println(df.format(4.00)); – Uncle Iroh Jun 30 '16 at 16:13
  • 2
    @dashrb The OP was very explicit about what he wanted. He wants to remove trailing zeroes. Do you understand what the word "trailing" means? – Peter Schorn Sep 12 '20 at 01:06
  • @UncleIroh FYI this provides correct solution even after removing the RoundingMode.HALF_UP but keeping #.### – Prabhat Gaur Jan 13 '21 at 18:04
  • "0.##" will return 4.32 and not round off value. – xiang Apr 18 '23 at 03:17