Java Math Rounding Sample Code

Many times as a Java programmer, you will need to manipulate numbers and Java has a nice set of methods in the Math package to help. There are well over 50 methods available in the Java math package, but I am just focusing on a few that have to do with math rounding.

The sample java program below makes gives a tutorial on using floor(), ceil(), and round() methods. The floor() method is intuitive in that it rounds the number down to the floor. Likewise, the ceil() method rounds the number up to the ceiling. Finally, the round() method round up or down to the nearest whole number.

Class Name Method Parameters Return Type Exceptions
Math floor() double double none
Math ceil() double double none
Math round() double long none

Java Math Rounding Source Code:


public class JavaMathRounding {
	public static void main( String[] args )
		//Round Down (ie: floor)
		double num1 = 100.10;
		double num2 = 100.99;
		System.out.println("\nRound Down: "+Math.floor(num1));
		System.out.println("Round Down: "+Math.floor(num2));
		//Round Up (ie: ceiling)
		double num3 = 100.10;
		double num4 = 100.99;
		System.out.println("\nRound Up: "+Math.ceil(num3));
		System.out.println("Round Up: "+Math.ceil(num4));
		//Rounding to Whole (ie: no decimals)
		double num5 = 100.10;
		double num6 = 100.99;
		System.out.println("\nRound Whole: "+Math.round(num5));
		System.out.println("Round Whole: "+Math.round(num6));	


Sample Java Math Rounding Output

Round Down: 100.0
Round Down: 100.0

Round Up: 101.0
Round Up: 101.0

Round Whole: 100
Round Whole: 101

Java References:

Add a Comment

Your email address will not be published. Required fields are marked *