Assuming the result of ceil
fits in the range of int
(or whatever the casted type may be), the cast is safe. Rounding errors only come into play when the number in question can't be expressed exactly in binary. For example, 0.5 can be expressed exactly as a binary number, but 0.1 cannot.
Since the result of ceil
is a integer, it can be expressed exactly in binary so there is no rounding error, and is thus safe to cast.
You can tell if a number can be expressed as a terminating or non-terminating value by expressing the number as a reduced fraction and looking at the denominator. If the denominator contains only factors of the base in question, it can be expressed exactly, otherwise it is an infinitely repeating number.
Going back to the example of 0.5 and 0.1, the reduced fractional representation of these numbers is 1/2
and 1/10
. Both of these numbers can be expressed exactly in decimal because both 2 and 10 contain only factors of 10. Only the first however can be expressed in binary because 10 has 5 as a factor, which is not a factor of 2.
In the case of integers, they can all be expressed as a fraction with a denominator of 1. And since 1 is a factor of all integers, any integer can be expressed exactly in any base (including 2).