Java Math: Rounding Numbers
The will be occasions within your program when you will need to round a floating point number to a whole number. This could be necessary if you are calculating averages of numbers that have decimal places and you need to maintain decimal accuracy in your calculations but you may want to display a rounded, easier on the eye number.
The round() method requires one argument and will round that number to the nearest integer. The general syntax is:
Math.round(x);
Let’s see how we might return a rounded number from simple average calculation in Java:
//Calculate the average of 3 numbers double averageNumber = ((23.54 + 34.225 + 4.42223) / 3); //Output the floating point average System.out.println(averageNumber); //Output the rounded average System.out.println(Math.round(averageNumber));
The output should be both the un-rounded and rounded average:
run: 20.729076666666668 21 BUILD SUCCESSFUL (total time: 0 seconds)
If you want to round down to the nearest whole numbers you can use the floor() methods. as the name suggest, as floors are usually under you, this method will take any floating point number and round it to the nearest lower whole number. This means that both the numbers 10.99 and 10.01 will be rounded down to 10. The general syntax is:
Math.floor()
Let’s see how we might return rounded down number from a variety of floating point numbers in Java:
//Round down and output two numbers System.out.println(Math.floor(10.99)); System.out.println(Math.floor(10.01)); //Create a couple of double variables double bigNumber01 = 23.89; double bigNumber02 = 23.19; //Output rounded down versions of each variable System.out.println(Math.floor(bigNumber01)); System.out.println(Math.floor(bigNumber02));
The output should be both rounded down values:
run: 10.0 10.0 23.0 23.0 BUILD SUCCESSFUL (total time: 0 seconds)
Notice that the rounded numbers retain a decimal point, this is because the floor() method returns a double.
Similar to the floor() method is the ceil() method, except this method will round up as the name ceil(ing) suggests – ceilings are usually over you. The general syntax is:
Math.ceil()
Let’s see how we might return rounded up number from a variety of floating point numbers in Java:
//Round up and output two numbers System.out.println(Math.ceil(10.99)); System.out.println(Math.ceil(10.01)); //Create a couple of double variables double bigNumber01 = 23.89; double bigNumber02 = 23.19; //Output rounded down versions of each variable System.out.println(Math.ceil(bigNumber01)); System.out.println(Math.ceil(bigNumber02));
The output should be both rounded down values:
run: 11.0 11.0 24.0 24.0 BUILD SUCCESSFUL (total time: 0 seconds)
Again, notice that the rounded numbers retain a decimal point, this is because the ceil() method returns a double.