[ACCEPTED]-Why Math.Ceiling returns double?-ceil

Accepted answer
Score: 33

double has a greater value range than int:

The Double 14 value type represents a double-precision 13 64-bit number with values ranging from 12 negative 1.79769313486232e308 to positive 11 1.79769313486232e308, as well as positive 10 or negative zero, PositiveInfinity, NegativeInfinity, and 9 Not-a-Number (NaN).

Double complies with 8 the IEC 60559:1989 (IEEE 754) standard 7 for binary floating-point arithmetic.

That 6 standard says that double has a 52-bit mantissa, which 5 means it can represent any integer up to 4 52 bits long without loss of precision.

Therefore 3 if the input is large enough, the output 2 doesn't fit inside an int (which only has 32 1 bits).

Score: 31

The documentation says about the return 6 value:

The smallest whole number greater 5 than or equal to a. If a is equal to NaN, NegativeInfinity, or 4 PositiveInfinity, that value is returned.

Therefore 3 the return value has to be double since 2 NaN, NegativeInfinity and PositiveInfinity 1 are fields of Double.

Score: 6

Math.Ceiling can return either a double or a decimal, depending on 10 the type passed in. In other words, the 9 output type of the method matches the input 8 type (quite sensibly).

They could have added 7 a third overload that takes an int and returns 6 an int, but there wouldn't have been much point 5 to this - the function would always just 4 return its input.

You seem to be assuming 3 that the purpose of Math.Ceiling is to cast a floating-point 2 value to an integer, but that's usually 1 not how it's used.

Score: 3

It has to return double in order to be complete. Any 8 math operation involving a NaN always returns 7 NaN. Thus if you pass a NaN to ceiling() function 6 one would not be able to return NaN, as 5 there is no equivalent in Int. Also given 4 that Double has a wider range what would 3 one return for those out of range integer 2 values ? What does one return for +/- inf 1 ?

Score: 0

Because double can contain larger numbers than 2 int or long. Same reason there's no implicit cast 1 from double to int.

More Related questions