1

I'm trying to format output for user/report appeal, and there are two criteria I'm finding to be in a bit of conflict.

First, the decimal values should line up (format on "%12.10f", predicted integer value range 0-99)

Second, the decimal shouldn't trail an excessive series of zeroes.

For example, I have output that looks like

  0.5252772000
  0.2053628186
 10.5234500000

But using a general formatting, I also end up with:

 0.53260000000
 0.52630000000
12.43540000000

In certain cases, and it looks kind of garbage.

Is there a simple way to solve this problem? The only solution I can come up with at the moment involves pre-interrogating the data before printing (instead of formatting it during print) which, while technically not expensive, just bugs me as being redundant data handling (ie I have to go through all data once to find the extrema of trailing zeroes to parse against it, and then set the format so that it can go through the data again to parse it)

Captain Prinny
  • 459
  • 8
  • 23

1 Answers1

0

You can set a DecimalFormat:

DecimalFormat format = new DecimalFormat("0.#");
for (float f : yourFloats){
    System.out.println(format.format(f));
}

This also works on doubles.

Roel Strolenberg
  • 2,922
  • 1
  • 15
  • 29
  • Tried this, from another thread, does not work. This solution rounds to one decimal place and does not preserve data. Further use of # creates a fixed decimal length but does nothing to solve needing a fixed width "starting" position, nor maintaining data. – Captain Prinny Jun 26 '15 at 20:54
  • Look at this thread: http://stackoverflow.com/questions/703396/how-to-nicely-format-floating-numbers-to-string-without-unnecessary-decimal-0 . – Roel Strolenberg Jun 26 '15 at 21:02
  • The third answer looks like it may have promise, will investigate it on monday. Doesn't seem to address the need for fixed width, but since it's a string value for the format, I should be able to finagle the integer parts of the string. – Captain Prinny Jun 28 '15 at 04:25