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!
Description. This function returns a floating-point value representing the nearest whole number that is greater than or equal to the value passed to it. If that value is an integer it will, by definition, be the value math. ceil() returns, albeit as float not an integer.
Returns of Ceil in Python As would be obvious, the ceil() function in Python returns a single numeric int type value, irrespective of whether the input was int or float. The value of the output is the smallest integer greater than or equal to the input number.
Return Value The ceil() function returns the integer as a double value.
ceil( ) differs from Math. round( ) in that it always rounds up, rather than rounding up or down to the closest integer. Also note that Math. ceil( ) does not round negative numbers to larger negative numbers; it rounds them up toward zero.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With