Double.MaxValue to integer is negative?

后端 未结 3 1004
日久生厌
日久生厌 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:13

    The C# Language Specification (Version 5.0) says the following in 6.2.1 "Explicit numeric conversions" (emphasis added):

    • For a conversion from float or double to an integral type, the processing depends on the overflow checking context (§7.6.12) in which the conversion takes place:

      • In a checked context, the conversion proceeds as follows:

        • If the value of the operand is NaN or infinite, a System.OverflowException is thrown.
        • Otherwise, the source operand is rounded towards zero to the nearest integral value. If this integral value is within the range of the destination type then this value is the result of the conversion.
        • Otherwise, a System.OverflowException is thrown.
      • In an unchecked context, the conversion always succeeds, and proceeds as follows.

        • If the value of the operand is NaN or infinite, the result of the conversion is an unspecified value of the destination type.
        • Otherwise, the source operand is rounded towards zero to the nearest integral value. If this integral value is within the range of the destination type then this value is the result of the conversion.
        • Otherwise, the result of the conversion is an unspecified value of the destination type.

    And in 7.6.12 "The checked and unchecked operators"

    For non-constant expressions (expressions that are evaluated at run-time) that are not enclosed by any checked or unchecked operators or statements, the default overflow checking context is unchecked unless external factors (such as compiler switches and execution environment configuration) call for checked evaluation.

    For conversions from double to decimal: "If the source value is NaN, infinity, or too large to represent as a decimal, a System.OverflowException is thrown". checked vs unchecked doesn't come into play (those deal with integral operations only).

提交回复
热议问题