Narrowing numeric conversions are those numeric conversions that possibly cause a loss of information. It is important to note that a loss of precision is not considered to be a loss of information. Thus, conversions to Single
or Double
are not considered narrowing. An narrowing numeric conversion is processed as follows:
Single
, Double
or Decimal
to an integral type, the effect depends on whether the compiler option to generate exceptions on integer overflow conditions is specified:
If the source is an integral type, the conversion succeeds if the source argument is within the range of the destination type, but throws a System.OverflowException
exception if the source argument is outside the range of the destination type
If the source is Single
, Double
or Decimal
, the source value is rounded up or down to the nearest integral value, and this integral value becomes the result of the conversion. If the source value is equally close to two integral values, the value is rounded to the value that has an even number in the least significant digit position. If the resulting integral value is outside the range of the destination type, a System.OverflowException
exception is thrown
If the source is an integral type, the conversion always succeeds, and simply consists of discarding the most significant bits of the source value
If the source is Single
, Double
or Decimal
, the conversion always succeeds, and simply consists of rounding the source value towards the nearest integral value. If the source value is equally close to two integral values, the value is always rounded to the value that has an even number in the least significant digit position.
Double
to Single
, the effect depends on whether the compiler option to generate exceptions on floating point overflow conditions is specified:
The Double
value is rounded to the nearest Single
value. If the Double
value is too small to represent as a Single
, the result becomes positive zero or negative zero. If the Double value is too large to represent as a Single, a System.Overflow
exception is thrown.
The Double
value is rounded to the nearest Single
value. If the Double
value is too small to represent as a Single
, the result becomes positive zero or negative zero. If the Double
value is too large to represent as a Single
, the result becomes positive infinity or negative infinity. If the Double
value is NaN, the result is also NaN.
Single
or Double
to Decimal
, the source value is converted to decimal representation and rounded to the nearest number after the 28th decimal place if required. If the source value is too small to represent as a decimal, the result becomes zero. If the source value is NaN, infinity, or too large to represent as a decimal, a System.OverflowException
exception is thrown.Decimal
to Single
or Double
, the decimal value is rounded to the nearest Double
or Single
value. While this conversion may lose precision, it never causes an exception to be thrown.