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

前端 未结 5 1102
清歌不尽
清歌不尽 2020-12-31 01:51

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

相关标签:
5条回答
  • 2020-12-31 02:10

    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
    
    0 讨论(0)
  • 2020-12-31 02:19

    It differs for negative values:

    double num = -1.3;
    double floor = Math.Floor(num); // = -2
    long cast = (long)num; // = -1
    
    0 讨论(0)
  • 2020-12-31 02:23

    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.

    0 讨论(0)
  • 2020-12-31 02:27

    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.
    0 讨论(0)
  • 2020-12-31 02:29

    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.

    0 讨论(0)
提交回复
热议问题