In C# the method Math.Ceiling
returns a double
value. Why does it not return int
?
double
has a greater value range than int
:
The Double value type represents a double-precision 64-bit number with values ranging from negative 1.79769313486232e308 to positive 1.79769313486232e308, as well as positive or negative zero, PositiveInfinity, NegativeInfinity, and Not-a-Number (NaN).
Double complies with the IEC 60559:1989 (IEEE 754) standard for binary floating-point arithmetic.
That standard says that double
has a 52-bit mantissa, which means it can represent any integer up to 52 bits long without loss of precision.
Therefore if the input is large enough, the output doesn't fit inside an int
(which only has 32 bits).
It has to return double in order to be complete. Any math operation involving a NaN always returns NaN. Thus if you pass a NaN to ceiling() function one would not be able to return NaN, as there is no equivalent in Int. Also given that Double has a wider range what would one return for those out of range integer values ? What does one return for +/- inf ?
The documentation says about the return value:
The smallest whole number greater than or equal to a. If a is equal to NaN, NegativeInfinity, or PositiveInfinity, that value is returned.
Therefore the return value has to be double since NaN, NegativeInfinity and PositiveInfinity are fields of Double.
Because double
can contain larger numbers than int
or long
. Same reason there's no implicit cast from double
to int
.
Math.Ceiling
can return either a double
or a decimal
, depending on the type passed in. In other words, the output type of the method matches the input type (quite sensibly).
They could have added a third overload that takes an int
and returns an int
, but there wouldn't have been much point to this - the function would always just return its input.
You seem to be assuming that the purpose of Math.Ceiling
is to cast a floating-point value to an integer, but that's usually not how it's used.