Math.ceil() issue. Am I losing my mind?

Ok I hope I am mising something here as I really don’t want this to be a bug.

The following piece of code returns 2. Per my understanding of the ceiling functionality, the result should be 3 because 7/3 is roughly 2.33333 and the ceiling should return 3.

Is this a bug or am I missing something? Thanks.

Integer pageNumber = (Integer) Math.ceil(7/3);

This returns 2 and not 3 as expected.

It works fine on other input. For example:

Integer pageNumber = (Integer) Math.ceil(8/5);

This returns 2 as expected.


This is probably because when you divide an Integer by an Integer you get an Integer back which has the same value as Decimal.round(RoundingMode.DOWN).

system.assertEquals(1, 8/5);
system.assertEquals(8/5, (8.0/5).round(RoundingMode.DOWN);

system.assertEquals(-1, -8/5);
system.assertEquals(-8/5, (-8.0/5).round(RoundingMode.DOWN);

system.assertEquals(2, 7/3);
system.assertEquals(7/3, (7.0/3).round(RoundingMode.DOWN);

If you know you have Integers and you want to get their ceiling, you could do something like:

public static Integer ceiling(Integer x, Integer y)
    return Math.ceil(Decimal.valueOf(x).divide(y, /*digits*/ 1));

Source : Link , Question Author : Richard N , Answer Author : Adrian Larson

Leave a Comment