0

my homework exercise gave skeleton of attendaces and my job was to name weeks so it maches values in arrays and get avarage attendance for each week and get output and the code is:

public class AttendanceTest {

    public static void main(String[] args) {
        final Integer CLASS_SIZE = 15;
        Integer[] attendances = {10, 14, 12, 9, 11, 15, 12, 13, 8, 14};
        final Integer ACADEMIC_WEEKS = 10;
        final String[] weeks = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10"};
        Double totalAvg;

        for (Integer week = 0; week < ACADEMIC_WEEKS; week++) {
            totalAvg = (double)(attendances[week]*100)/CLASS_SIZE;
            System.out.println(weeks[week] + "    " +totalAvg);
        }
    }
}

and gives output of:

1    66.66666666666667
2    93.33333333333333
3    80.0
4    60.0
5    73.33333333333333
6    100.0
7    80.0
8    86.66666666666667
9    53.333333333333336
10    93.33333333333333

how can i round the output to 2 decimal point using String.format and/or .places?

so the output will be:

1   66.67
2   93.33
3   80.00
4   60.00
5   73.33
6  100.00
7   80.00
8   86.67
9   53.33
10  93.33
Guminik
  • 5
  • 3

1 Answers1

1

Use printf, not println:

System.out.printf("%s\t%.2f%n", weeks[week], totalAvg);
  • %s prints the first parameter given as string
  • \t prints a tab
  • %.2f prints the second parameter given as float with 2 decimal digits
  • %n prints a new line
Oneiros
  • 4,328
  • 6
  • 40
  • 69
  • im not sure why but the output is:" 1 66,672 93,333 80,004 60,005 73,336 100,007 80,008 86,679 53,3310 93,33" im not sure where did that 1 came from and it doesnt round to well – Guminik Nov 10 '17 at 11:29
  • You need to add `%n` at the end of the format to have a newline (like `println` – AxelH Nov 10 '17 at 11:55
  • Forgot the \n at the end – Oneiros Nov 10 '17 at 12:02
  • `\n` is OS dependent, not `%n`, see [What's up with Java's “%n” in printf?](https://stackoverflow.com/questions/1883345/whats-up-with-javas-n-in-printf) – AxelH Nov 10 '17 at 12:14
  • You’re right, thanks – Oneiros Nov 10 '17 at 12:17
  • In the end, everything is explained in [Formatter](https://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html). This is a must to read ! – AxelH Nov 10 '17 at 12:19