For some decimal values, when we convert the type from decimal to double, a small fraction is added to the result.
What makes it worse, is that there can be two "equal" decimal values that result in different double values when converted.
decimal dcm = 8224055000.0000000000m; // dcm = 8224055000
double dbl = Convert.ToDouble(dcm); // dbl = 8224055000.000001
decimal dcm2 = Convert.ToDecimal(dbl); // dcm2 = 8224055000double
dbl2 = Convert.ToDouble(dcm2); // dbl2 = 8224055000.0
decimal deltaDcm = dcm2 - dcm; // deltaDcm = 0
double deltaDbl = dbl2 - dbl; // deltaDbl = -0.00000095367431640625
Note that there IS a double representation of the converted decimal value which is closer.
It violates section 6.2.1 of the C# spec:
For a conversion from decimal to float or double, the decimal value is rounded to the nearest double or float value. While this conversion may lose precision, it never causes an exception to be thrown.
This is a question originally posted to StackOverflow by me, which can be reached via the following URL: