Why do round() and ceil() not return an integer?

Wookai picture Wookai · Aug 10, 2009 · Viewed 21.5k times · Source

Once in a while, I find myself rounding some numbers, and I always have to cast the result to an integer:

int rounded = (int) floor(value);

Why do all rounding functions (ceil(), floor()) return a floating number, and not an integer? I find this pretty non-intuitive, and would love to have some explanations!

Answer

Sean A.O. Harney picture Sean A.O. Harney · Aug 10, 2009

The integral value returned by these functions may be too large to store in an integer type (int, long, etc.). To avoid an overflow, which will produce undefined results, an application should perform a range check on the returned value before assigning it to an integer type.

from the ceil(3) Linux man page.