Are there any reasons one would prefer to use Math.Floor vs casting to an integral type?
double num;
double floor = Math.Floor(num);
OR
In addition to the other answers, don't forget that casting might fail where Floor
would succeed:
decimal d = decimal.MaxValue;
decimal f = Math.Floor(d); // succeeds
long l = (long)d; // fails
It differs for negative values:
double num = -1.3;
double floor = Math.Floor(num); // = -2
long cast = (long)num; // = -1
Math.Floor
is a fundamentally different operation from truncation because it handles negative numbers differently. Math.Floor(-1.5) == -2.0
, while (int)-1.5 == -1
.
There are some differences between casting to an integral type and using Math.Floor:
Even if you're only dealing with positive values, a double
value doesn't always fit in a long
.
See ranges of long and double on MSDN.