Round up a number using ceil method of Java Math class

This example shows how to round up a number using the ceil method of the Java Math class. The ceil method returns a number that is equal to or greater than the given number and is equal to an integer.

How to round up a number using the Math class?

Use the ceil method of the Java Math class to round up a number.

This method returns the smallest double number which is equal to or greater than the argument and is equal to an integer.

Output

Please note that the Math.ceil(-21.2) method returns -21.0 not -22.0. That is because -21 is greater than -21.2.

Please also note that the ceil method returns a double. You may need to cast it to an appropriate data type from the double value.

Consider below given example.

Output

Not what we expected. Dividing 9 by 2 equals to 4.5 and rounding it up should give us 5.0 as a result. Instead, the result is 4.0. That is because a and b both are integers and dividing an integer with another integer always rounds the result which is 4.0. Getting ceil of 4.0 returns 4.0.

One way to fix it is to cast the division operation to a double value as given below

Output

This example is a part of the Java Math class tutorial with examples.

Please let me know your views in the comments section below.

About the author

RahimV

RahimV

My name is RahimV and I have over 16 years of experience in designing and developing Java applications. Over the years I have worked with many fortune 500 companies as an eCommerce Architect. My goal is to provide high quality but simple to understand Java tutorials and examples for free. If you like my website, follow me on Facebook and Twitter.

Add Comment

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