C# – Why does Math.Floor(Double) return a value of type Double

cfloormath

I need to get the left hand side integer value from a decimal or double. For Ex: I need to get the value 4 from 4.6. I tried using Math.Floor function but it's returning a double value, for ex: It's returning 4.0 from 4.6. The MSDN documentation says that it returns an integer value. Am I missing something here? Or is there a different way to achieve what I'm looking for?

Best Answer

The range of double is much wider than the range of int or long. Consider this code:

double d = 100000000000000000000d;
long x = Math.Floor(d); // Invalid in reality

The integer is outside the range of long - so what would you expect to happen?

Typically you know that the value will actually be within the range of int or long, so you cast it:

double d = 1000.1234d;
int x = (int) Math.Floor(d);

but the onus for that cast is on the developer, not on Math.Floor itself. It would have been unnecessarily restrictive to make it just fail with an exception for all values outside the range of long.