Java Basic Examples

Round up a number using ceil method of Java Math class

This Java example shows how to round up a number using ceil method of Java Math class.

How to round up a number using Math class?

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

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

Output

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

Please also note that ceil() method returns double. You may need to cast it to appropriate data type from 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 double as given below

Output

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

Want to learn quickly?
Try one of the many quizzes. I promise you will not be disappointed.

Tags