Error in converting decimal values to double - by Hamed Irchi

Status : 

  Won't Fix<br /><br />
		Due to several factors the product team decided to focus its efforts on other items.<br /><br />
		A more detailed explanation for the resolution of this particular item may have been provided in the comments section.

Sign in
to vote
ID 498340 Comments
Status Closed Workarounds
Type Bug Repros 1
Opened 10/18/2009 2:30:00 AM
Access Restriction Public


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.

Code sample:

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:

Sign in to post a comment.
Posted by Microsoft on 6/25/2010 at 10:59 AM
Thanks for the suggestion. Unfortunately, we are not making investments in this area in the current version of .NET. We are however, keeping the bug so that we can consider it in a future version of the product.

Best Regards,
Mircea Trofin,
Posted by Microsoft on 11/3/2009 at 2:22 PM
Hi Iravanchi,

Thanks for taking the time to report this issue. This has already received quite a bit of discussion on the StackOverflow link you included. The difference in conversion of numbers that are the "same" comes from the differences in significant digits. Convert.ToDecimal(Double) only preserves 15 significant digits, so you'll get a different binary representation of the Decimal after it is converted back, since the Decimal type maintains significant digits. The two Decimals aren't actually the same when you look at the underlying representation.

In general, Double only guarantees 15 decimal digits of precision. The extra 1 in the least significant digits isn't something we will fix for .NET Framework 4.0. However, I'm going to keep this issue active so that we can look at it for our next release, and see if we can fix it earlier in the product cycle.

Base Class Libraries
Posted by Microsoft on 10/19/2009 at 3:41 AM
Thank you for your feedback, We are currently reviewing the issue you have submitted. If this issue is urgent, please contact support directly(