0

massTotal is printing out as a number ending in ".0" no matter what the decimal should be. The massCounter[] indexes are doubles. How do I make it round to the first decimal place, instead of to the whole number?

public static double massTotal(double[] massCounter) {
    double massTotal = 0.0;
    for (int i = 0; i < massCounter.length; i++) {
        massTotal += Math.round(massCounter[i] * 10.0 / 10.0);
    }
    return massTotal;
}

Thanks!

  • I believe this question can answer your question: https://stackoverflow.com/questions/153724/how-to-round-a-number-to-n-decimal-places-in-java?rq=1 , specifically DecimalFormat – reden Nov 22 '17 at 07:16
  • What's the point of `* 10.0 / 10.0`? – shmosel Nov 22 '17 at 08:23
  • 2
    I think you meant to do `Math.round(massCounter[i] * 10.0) / 10.0`. – shmosel Nov 22 '17 at 08:25

1 Answers1

1

Your Math.round function is basically rounding everything, i.e.

1.5 -> 2

22.4 -> 22

So therefore when they all get totalled in the method, it will always be x.0, which is just printing a whole number as a double, showing the first .0.

What you could do, is to completely remove the Math.round and then print the result with using String.format and it will show you the output with one decimal place.

String.format("%.1f", massTotal(myArray))

Or even easier, if you are allowed to use Java8 capabalities:

double total = DoubleStream.of(myArray).sum();
System.out.println(String.format("%.1f", total));

Online example

Community
  • 1
  • 1
achAmháin
  • 4,176
  • 4
  • 17
  • 40