Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 467
Wookai Avatar asked Aug 10 '09 08:08

Wookai


People also ask

Does Math ceil return an int?

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.

Does Python ceil return an int?

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.

What is the return value of ceil ()?

Return Value The ceil() function returns the integer as a double value.

What is the difference between ceil and round?

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.


1 Answers

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.

like image 140
Sean A.O. Harney Avatar answered Sep 28 '22 05:09

Sean A.O. Harney