Home » Questions » Computers [ Ask a new question ]

floating point - How to convert a Decimal to a Double in C#? -

"I want to use a Track-Bar to change a Form's opacity.
This is my code:
decimal trans = trackBar1.Value / 5000;
this.Opacity = trans;

When I build the application, it gives the following error:

Cannot implicitly convert type decimal to double

I have tried using trans and double, but then the Control doesn't work. This code worked fine in a past VB.NET project.

c# floating-point type-conversion double decimal

ShareShare a link to this question Copy linkCC BY-SA 4.0

Improve this question

Follow this question to receive notifications

edited Feb 26 at 3:31

community wiki

45 revs, 35 users 9%Eggs McLaren"

Asked by: Guest | Views: 157
Total answers/comments: 4
bert [Entry]

"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;"
bert [Entry]

"A more generic answer for the generic question ""Decimal vs Double?"":
Decimal is for monetary calculations to preserve precision. Double is for scientific calculations that do not get affected by small differences. Since Double is a type that is native to the CPU (internal representation is stored in base 2), calculations made with Double perform better than Decimal (which is represented in base 10 internally)."
bert [Entry]

"Your code worked fine in VB.NET because it implicitly does any casts, while C# has both implicit and explicit ones.

In C# the conversion from decimal to double is explicit as you lose accuracy. For instance 1.1 can't be accurately expressed as a double, but can as a decimal (see ""Floating point numbers - more inaccurate than you think"" for the reason why).

In VB the conversion was added for you by the compiler:

decimal trans = trackBar1.Value / 5000m;
this.Opacity = (double) trans;

That (double) has to be explicitly stated in C#, but can be implied by VB's more 'forgiving' compiler."
bert [Entry]

"Why are you dividing by 5000? Just set the TrackBar's Minimum and Maximum values between 0 and 100 and then divide the Value by 100 for the Opacity percentage. The minimum 20 example below prevents the form from becoming completely invisible:

private void Form1_Load(object sender, System.EventArgs e)
TrackBar1.Minimum = 20;
TrackBar1.Maximum = 100;

TrackBar1.LargeChange = 10;
TrackBar1.SmallChange = 1;
TrackBar1.TickFrequency = 5;

private void TrackBar1_Scroll(object sender, System.EventArgs e)
this.Opacity = TrackBar1.Value / 100;