2

When converting a decimal to a double, sometimes there is some unexpected truncation. For example:

        decimal dec = -96.31614743511301m;
        double dbl = Convert.ToDouble(dec);  // dbl = -96.316147435113, why?

For other values it works as expected:

        decimal dec2 = -96.269592225955307m;
        double dbl2 = Convert.ToDouble(dec2); // dbl2 = -96.269592225955307, expected

Note that the second example which works actually has more decimal places than the first which doesn't. Also, the first value can be converted successfully into a double using this convoluted code:

        dbl = Convert.ToDouble(dec.ToString()); // dbl = -96.31614743511301, expected

So why is the double value truncated in the first example?

1 Answers1

3

Decimal and double are stored differently with different accuracy... see here - Difference between decimal, float and double in .NET?

Community
  • 1
  • 1
Rashack
  • 4,667
  • 2
  • 26
  • 35
  • Storage details aside, it seems that if both double and decimal are capable of storing the value -96.31614743511301, then conversion from one to the other should work without truncating the value. Why does this work without truncation... double dbl = Convert.ToDouble("-96.31614743511301"); but this results in truncation... decimal dec = -96.31614743511301m; double dbl = Convert.ToDouble(dec); – James Goodrich Nov 23 '12 at 04:48
  • 1
    This looks like a bug... http://stackoverflow.com/questions/1584314/conversion-of-a-decimal-to-double-number-in-c-sharp-results-in-a-difference?rq=1 – James Goodrich Nov 23 '12 at 20:10