-2

I'm trying to format my decimal output so that it cuts/rounds decimals so that they only have four digits; Two in front and two in back.

for (int i = 0; i < planets.length; i++) {
        System.out.print(planets[i]);
        System.out.printf("     %4.2f", planetDiameter[i]);
        System.out.printf("     %4.2f", planetMass[i]);
        System.out.printf("     %4.2f\n", gravity[i]);
    }

But this doesn't cut or round the front of the decimal at all. Is there a way to shorten the front part of the decimal so that I don't get a large number?

Ethan Stedman
  • 11
  • 1
  • 6
  • 6
    So if the number is `1234.5678` you want the output to be `34.57`? what do you mean by _"cut or round the front of the decimal"_? – Jim Garrison Jan 02 '18 at 20:42
  • printf or format won't do what you are looking for. You can split your number as a string into 2 parts, using decimal as a splitter and then round them separately and concatenate them back. I am just curious on the usecase of this problem though since you are literally changing the value of the number completely by doing that. – moonlighter Jan 02 '18 at 21:46

1 Answers1

0

I'm going to assume you have some sort of special class for these Planets, which you totally should; and that you store each instance of that class in the array named planets. Therefore, you should create Getters and Setters to get the values of each planet, since I don't think your code works as it is. Regardless, I salute you for your determination.

If you want to round the number to 2 decimal places, and round it's result to the nearest ceiling (I don't really know how to express this, see code):

DecimalFormat df = new DecimalFormat("####.##");
df.setRoundingMode(RoundingMode.CEILING);
for (int i = 0; i < planets.length; i++) {
    System.out.print(planets[i]);
    System.out.println("     " + df.format(planetDiameter[i]));
    System.out.println("     " + df.format(planetMass[i]));
    System.out.println("     " + df.format(gravity[i]) + "\n");
}

The parameters in the declaration of DecimalFormat, mean the amount of numbers that you want to display; then the rounding mode indicates whether you want to raise the number to the nearest-high value, or lower the number to the nearest-low value.

However, I can't test this since, well, I don't have the planets array, thus I don't have data to try.

You can try it to see how it works, and I'll give you this, which is the original post from where I got the idea, nice info.

Good luck man.

Rolin Azmitia
  • 129
  • 1
  • 2
  • 14