Skip to content

Round up a number using ceil method of Java Math class

The Math ceil method 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 ceil method of the Math class?

We can 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 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

Leave a Reply

Your email address will not be published.