Average of 3 numbers (included number rounding)

The following code snippet calculates the average of 3 numbers. The average is rounded by different rounding methods.

Code Explanation

LineDescription
2Method header of the method roundDouble() with the input parameters value of type double and decimalPoints of type integer. The method is static, private and of type double
3The Math.pow() method calculates the power of a number by raising the first argument (10) to the second argument (decimalPoints)
4Returns the rounded value via the Math.round() method
9Declares the variables a, b, c and avg of type double
12 – 14Initializes the variables a, b and c with the values 11.54, 7.73 and 10.54
16Calculates the average of variable a, b and c
18Outputs the 3 numbers and the average value (without rounding)
19 – 22Outputs the mean value via the methods String.format(), Math.round() and the user-defined method roundDouble()
class AvgNumbers {
	private static double roundDouble(double value, int decimalPoints) {
		double d = Math.pow(10, decimalPoints);
		return Math.round(value * d) / d;
	 }

	public static void main(String[] args) {
		// declare variables
		double a, b, c, avg; 

		// initialize variables
		a = 11.54;
		b = 7.73;
		c = 10.54;
		
		avg = (a + b + c) / 3;

		System.out.println("Average of " + a + ", " + b + " and " + c + " is: " + avg);
		System.out.println("Rounded value:\n"
							+ String.format("%1.2f", avg) + "\n"
							+ Math.round(avg) + "\n"
							+ roundDouble(avg, 2) + "\n");
	}
}
Output
Average of 11.54, 7.73 and 10.54 is: 9.936666666666666
Rounded value:
9.94
10
9.94