I have the following code to test the conversion from double to long:
double dVal = (double)(long.MaxValue); // 9.2233720368547758E+18;
if (dVal <= long.MaxValue && dVal >= long.MinValue)
{
long lVal1 = (long)(dVal); // gives -9223372036854775808 !!!
Console.WriteLine($"lVal1 = {lVal1}");
long lVal2 = Convert.ToInt64(dVal); // gives System.OverflowException
}
I expected lVal1/2 to be 9223372036854775807 or 9223372036854775800 because of the truncation or rounding in the double type.
How can I convert double to long correctly for all cases? Is there something in the framework already or do I need to implement it?