0

I was wondering on how to remove trailing 0s from whole numbers in my java program For example: 100.0 -> 100 However, for numbers like 1285.71 to remain the same.

I just need the trailing 0's from whole numbers removed, while still retaining the double value. I've tried:

    double s = x / y;
    String pattern = "0.#";

    DecimalFormat decimalFormat = new DecimalFormat(pattern);
    System.out.println(decimalFormat.format(Double.valueOf(s)) );

However, does not working and i still get the annoying 0 after a whole number (100.0) Any help or insight would be much appreciated, cheers for your time.

utnicho
  • 49
  • 7

1 Answers1

0

Because you're using DecimalFormat for representing your numbers, then there are a few points to remember about the pattern:

  • 0 – prints a digit if provided, 0 otherwise
  • # – prints a digit if provided, nothing otherwise
  • . – indicate where to put the decimal separator
  • , – indicate where to put the grouping separator

The integer part is never discarded. If you provide a pattern like this: "0.#", then it will output the prefix and the first digit in the postfix if it's not zero. For example, 12345.5 will output the same, but 12345.0 will output 12345.

In case your digits after the postfix exceed the number of postfix patterns you provide, then those digits will be discarded, for example your pattern is 0.#" and your input is 123.45 then the output will be 123.4.

Then you can change your pattern to "0.##" to make it works for both 100.0 and 1285.71

Nam V. Do
  • 630
  • 6
  • 27