Search code examples
cfloorceil

Is it safe to cast result of ceil to integer?


ceil function in C is declared as double ceil(double). Is it safe to cast return value of the function to int? I mean is there any guarantee that the following will never occur (the sample is just to illustrate of what I mean)?

double r = ceil(234235.53453);
// imagine r = 234235.9999999 due to round errors or
// due to the peculiarities of the machine arithmetics, etc.
int i = (int)r;
// i = 234235, but must be 234236

Of course, I know that the range of double is large than the range of int, so the cast may fail. My question is not about it, but about rounding errors or machine arithmetics side effects.


Solution

  • A 64-bit double represents integers of up to 2 in power 53 exactly. Integers larger than that do not have any fractional part when represented as double.

    In other words, you can safely cast the result of ceil or floor to an integer, as long as that integer can hold the value.