Search code examples
c#floating-pointtype-conversiondoubledecimal

How to convert Decimal to Double in C#?


I want to assign the decimal variable trans to the double variable this.Opacity.

decimal trans = trackBar1.Value / 5000;
this.Opacity = trans;

When I build the app it gives the following error:

Cannot implicitly convert type decimal to double


Solution

  • An explicit cast to double like this isn't necessary:

    double trans = (double) trackBar1.Value / 5000.0;
    

    Identifying the constant as 5000.0 (or as 5000d) is sufficient:

    double trans = trackBar1.Value / 5000.0;
    double trans = trackBar1.Value / 5000d;