C# – Math.Floor vs cast to an integral type in C#


Are there any reasons one would prefer to use Math.Floor vs casting to an integral type?

double num;
double floor = Math.Floor(num);


double num;
long floor = (long)num;

Best Solution

There are some differences between casting to an integral type and using Math.Floor:

  1. When casting to an integral type, you'll end up with an integral type (obviously). So if you want to keep the number as a double, using Floor is easier.
  2. As a consequence of 1, casting will not work correctly if the given number is too large to be represented by the given integral type (a double can represent much larger numbers than a long).
  3. Floor rounds towards negative infinity. Casting rounds towards zero.