Why Math.Ceiling returns double?

C#.NetCeil

C# Problem Overview


In C# the method Math.Ceiling returns a double value. Why does it not return int?

C# Solutions


Solution 1 - C#

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).

Solution 2 - C#

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.

Solution 3 - C#

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.

Solution 4 - C#

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 ?

Solution 5 - C#

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMaciejLisCKView Question on Stackoverflow
Solution 1 - C#JonView Answer on Stackoverflow
Solution 2 - C#RoflcoptrExceptionView Answer on Stackoverflow
Solution 3 - C#MusiGenesisView Answer on Stackoverflow
Solution 4 - C#mP.View Answer on Stackoverflow
Solution 5 - C#Andrew CooperView Answer on Stackoverflow