0

I have the following code and my output is working but I don't know how to use the printf to make this output (66.67%) instead of 66.66666666666667%, just for an example. Any help is appreciated!

public static void evenNumbers(Scanner input) 
{
     int numNums = 0;
     int numEvens = 0;
     int sum = 0;

 while (input.hasNextInt()) 
  {
     int number = input.nextInt();
      numNums++;
     sum += number;
   if (number % 2 == 0) 
   {
        numEvens++;
   }
  }
     System.out.println(numNums + " numbers, sum = " + sum);
     System.out.println(numEvens + " evens " + (100.0* numEvens / numNums + "%"));



}

Thank you

user2268587
  • 179
  • 2
  • 2
  • 10

4 Answers4

6

You can use the printf modifier %.2f to get only two decimal places.

yamafontes
  • 5,552
  • 1
  • 18
  • 18
3

Use String.format and %.2f:

String.format("%d evens %.2f%%", numEvens, 100.0 * numEvens / numNums);
Robin Krahl
  • 5,268
  • 19
  • 32
  • Thank you!! I got it to this now apparently I need it to say 8 evens (66.67%), where would it be good to stick in the parentheses? System.out.printf("%d evens %.2f%%", numEvens, 100.0 * numEvens / numNums); – user2268587 Oct 24 '13 at 21:25
  • You would write `"%d evens (%.2f%%)"`. Maybe [this article](http://javarevisited.blogspot.de/2012/08/how-to-format-string-in-java-printf.html) helps you understand string formatting in Java. – Robin Krahl Oct 24 '13 at 21:32
0

You can use Math.round on the answer before you print it:

     System.out.println(numEvens + " evens " + Math.round((100.0* numEvens / numNums)*100)/100.0d + "%"));
spydon
  • 9,372
  • 6
  • 33
  • 63
0

Don't use printf here. Instead, use MessageFormat or DecimalFormat.getPercentInstance().

String format = "{numbers: {0, number, integer}," +
                " sum: {1, number,  integer}\n" +
                "evens: {2, number, integer}," +
                " {3, number, percent}"
String message = MessageFormat.format(format,
    new Object[]{numNums, sum, numEvens, ((double) numEvens)/ numNums)});
System.out.println(message); 
Eric Jablow
  • 7,874
  • 2
  • 22
  • 29