Double.MaxValue to integer is negative?

后端 未结 3 1010
日久生厌
日久生厌 2020-12-17 09:31

Why does Double.MaxValue casted to an integral type results in a negative value, the smallest value of that type?

double maxDouble = double.MaxValue;       /         


        
3条回答
  •  别那么骄傲
    2020-12-17 10:01

    It seems the default behaviour here is unchecked, viz that unless you explicitly specify checked, the overflow goes undetected:

     double maxDouble = double.MaxValue;       // 1.7976931348623157E+308
     long uncheckedMaxDoubleLong = (long)maxDouble;    // -9223372036854775808
     long checkedMaxDoubleLong = checked((long)maxDouble); // ** Overflow Exception
    

    In hindsight, attempting direct conversion from double to long without validating or constraining the input first is ill advised due to 2 aspects:

    • numeric range mismatches / potential for overflow
    • rounding considerations

    So, a better bet here may have been to use Convert.ToInt64:

     var convertedDouble = Convert.ToInt64(maxDouble);    // ** OverflowException
    

    As this internally does the checked checking for you, and takes an opinion on rounding, viz:

     return checked((long)Math.Round(value));
    

提交回复
热议问题