2

I am trying to convert a double to a decimal using Convert.ToDecimal function. The problem is that somehow .net chooses to omit decimal digits depending on the size of original double variable.

Take the following example:

        double d = 2999247013.972682;
        decimal convDecimal = Convert.ToDecimal(d);
        decimal realDecimal = 2999247013.972682M;

        Console.WriteLine(d);
        Console.WriteLine(convDecimal);
        Console.WriteLine(realDecimal);

Which produces the following output:

2999247013,97268  // comments: (actual value 2999247013,972682)
2999247013,97268  // comments: (actual value 2999247013,97268)
2999247013,972682 // comments: (actual value 2999247013,972682)

(',' is the decimal separator on current locale)

What i am trying to achieve is to use a Convert.ToDecimal(d) and get the decimal number 2999247013,972682.

Any thoughts anyone?

Nikos Tsokos
  • 3,226
  • 2
  • 34
  • 41

2 Answers2

3

It's because the Decimal value returned can only have a maximum of 15 signification digits. From MSDN.

The Decimal value returned by this method contains a maximum of 15 significant digits. If the value parameter contains more than 15 significant digits, it is rounded using rounding to nearest. The following example illustrates how the Convert.ToDecimal(Double) method uses rounding to nearest to return a Decimal value with 15 significant digits.

Therefore, if there are more than 15 significant digits it will be rounded, which is what is happening in your case since the double value you're passing has 16 significant digits.

keyboardP
  • 68,824
  • 13
  • 156
  • 205
  • So as far as i can tell, the problem is that Convert.ToDecimal cannot handle more than 15 significant digits, even though Decimal as a type clearly supports this value. – Nikos Tsokos Oct 22 '12 at 12:03
  • The issue isn't that `Decimal` can support more digits, it's that the `Double` value is limited. Decimals are more precise than doubles, so the limiting factor is the double you're passing into the method. – keyboardP Oct 22 '12 at 12:18
  • OK. Things are starting to make sense now. Thank you for all the info. – Nikos Tsokos Oct 22 '12 at 12:42
  • No problem, hope it was useful. – keyboardP Oct 22 '12 at 12:43
0

As it is mentioned Here double data type in .net has 15-16 digits and I guess in your case it is 15 so it omits the last digit. Why are you using double in the first place? You can read double vs decimal for more information about these types and their usages.

Community
  • 1
  • 1
manman
  • 4,743
  • 3
  • 30
  • 42