Why does Double.MaxValue
casted to an integral type results in a negative value, the smallest value of that type?
double maxDouble = double.MaxValue; // 1.7976931348623157E+308
long maxDoubleLong = (long) maxDouble; // -9223372036854775808
I'd understand a compiler error if it's too large or an OverflowException
at runtime or if i'd use unchecked
that the conversion might not throw an exception, but the result becomes undefined and incorrect(negative).
Also strange is that the value is long.MinValue
:
bool sameAsLongMin = maxDoubleLong == long.MinValue; // true
By the way, the same happens if i cast it to int
:
int maxDoubleInt = (int)maxDouble; // -2147483648
bool sameAsIntMin = maxDoubleInt == int.MinValue; // true
If it try to cast it to decimal
i get an OverflowException
at runtime
decimal maxDoubleDec = (decimal)maxDouble; // nope
Update: it seems that Michael's and Barre's answers hit the nail on the head, if i use checked
explicitly i get an OverflowException
:
checked
{
double maxDouble = double.MaxValue; // 1.7976931348623157E+308
long maxDoubleLong = (long) maxDouble; // nope
}
maxDoubleInt
. – Confluent