68

I have a variable which is storing as decimal:

decimal firststYrComp = Int16.Parse(tb1stYr.Text.ToString());

Now I have this to get typecasted into Double? How do I do that? Thanks!

NoWar
  • 36,338
  • 80
  • 323
  • 498
RG-3
  • 6,088
  • 19
  • 69
  • 125
  • 2
    Any reason you wouldn't want to use Double.Parse(tb1stYr.Text.ToString()) in the first place? – sarvesh Apr 06 '11 at 18:57
  • Yes! I want to store integer into this format: 00.000. Decimal does that. Can double does that too? Just out of curiosity! – RG-3 Apr 06 '11 at 19:07
  • 2
    NET - I wouldn't normally say anything but you really should think about changing your Display Name its extremely unprofessional. – Security Hound Apr 06 '11 at 19:13

3 Answers3

101

You answered your own question—Just cast it to a double:

decimal x  = 3.141592654M ;
double  pi = (double) x ;
Nicholas Carey
  • 71,308
  • 16
  • 93
  • 135
  • 2
    It would be neat if you include a comment with the representation of the result of the cast. – Bojidar Stanchev Aug 22 '19 at 14:35
  • 1
    Can casting a `decimal` to a `double` ever fail though? What happens when it's a narrowing-conversion? – Dai Oct 14 '20 at 15:16
  • try to cast 10500000000.000000000000, you'll get 10499999999.999998 with .net6! (works with .net 4.7.2) – Thomas Dec 09 '22 at 13:19
  • @Thomas — Binary floating point traces precision for range. You need to read Goldberg's 1991 paper, [_What Every Computer Scientist Should Know About Floating-Point Arithmetic_](https://dl.acm.org/doi/pdf/10.1145/103162.103163). See also this website: [_What Every Programmer Should Know About Floating-Point Arithmetic, Or, Why Don’t My Numbers Add Up?_](https://floating-point-gui.de/) – Nicholas Carey Dec 09 '22 at 18:08
42

You can use decimal's built in converter.

decimal decimalValue = 5; 
double doubleValue = decimal.ToDouble(decimalValue);
Chuck Savage
  • 11,775
  • 6
  • 49
  • 69
17

Just Try

Decimal yourDecimal = 3.222222m;

Convert.ToDouble(yourDecimal);
anishMarokey
  • 11,279
  • 2
  • 34
  • 47