0

I am having a hard time with a homework problem getting my program to output a percentage properly. My goal is to just have my percentages be two decimal places out, even if it is 0.00%. Keep in mind, this is a level one programming course so the solution should be fairly basic, I just don't know why I can't see it. Thank you for your help.

I get these outputs:

supposed to be > 7 evens (100.00%) mine > 7 evens (100.0%)

supposed to be > 4 evens (36.36%) mine > 4 evens (36.36363636363637%)

Below is my code:

while(input.hasNextInt()) {



    int num = input.nextInt();
    totalcount++;
    totalsum = totalsum + num;

    if(num % 2 == 0) {

        totaleven++;

    }

}

double percent = (((double)totaleven/totalcount) * 100.00); <<< this right here
System.out.println(totalcount + " numbers, sum = " + totalsum);
System.out.println(totaleven + " evens " + "("+percent+"%)");

}

JD112
  • 87
  • 1
  • 7
  • http://stackoverflow.com/questions/2538787/how-to-display-an-output-of-float-data-with-2-decimal-places-in-java – jlars62 Nov 11 '13 at 19:34
  • Your question is answered here: [How to round a number to n decimal places in Java](http://stackoverflow.com/questions/153724/how-to-round-a-number-to-n-decimal-places-in-java) Look at stack-overflows suggested answers before asking a question. – Serdalis Nov 11 '13 at 19:34
  • I read that and was aware of that. I asked for a really basic solution. I should of stated another way other than printf. Thank you. – JD112 Nov 11 '13 at 19:41

1 Answers1

0

If you want to actually cut the digits, you can use Math.round() for example. If you just want to limit the output to a given amount of digits, you can use String.format() and give it a fixed width like "%6.2f%%" (read: 6 digits wide total (including the . ), 2 digits for the fraction, followed by a %).

TwoThe
  • 13,879
  • 6
  • 30
  • 54