tags:

views:

100

answers:

3

Every time I use Math.Round/Floor/Ceiling I always cast to int (or perhaps long if necessary). Why exactly do they return double if it's always returning an integer.

+8  A: 

The result might not fit into an int (or a long). The range of a double is much greater.

Approximate range of double: ±5.0 × 10−324 to ±1.7 × 10308

(Source)

Mark Byers
They said or long in the question.
bwawok
The point remains the same. A `double` can be larger than 9223372036854775807.
dan04
@Mark - I figured this would be the reason but just wanted to make sure. Obviously rounding to an integer *bigger* than a long is rare for *most applications*, Microsoft still had to implement it to make sense mathematically. Thanks!
TheCloudlessSky
A: 

There is no reason given on the docs that I could find. My best guess is that if you are working with doubles, chances are you would want any operations on doubles to return a double. Rounding it to cast to an int was deemed by the language designer less common then rounding and keeping as a double.

You could write your own method that cast it to an int for you in about 2 lines of code, and much less work than posting a question on stack overflow...

bwawok
Sure it's trivial to write your own, but Mark's answer provides insight. StackOverflow is not always about the 'how', I also like it for the 'why' :)
Si
-1 - I know *how*, I'm wondering *why*. Your answer doesn't even make sense.
TheCloudlessSky
+1  A: 

I agree with Mark's answer that the result might not fit in a long, but you might wonder: what if C# had a much longer long type? Well, here's what happens in Python with it's arbitary-length integers:

>>> round(1.23e45)
1229999999999999973814869011019624571608236032

Most of the digits are "noise" from the floating-point rounding error. Perhaps part of the motivation for Round/Floor/Ceiling returning double in C# was to avoid the illusion of false precision.

An alternative explanation is that the .NET Math module uses code written in C, in which floor and ceil return floating-point types.

dan04