Convert Decimal to Double?

2019-01-04 05:38发布

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 tried using trans and double but then the control doesn't work. This code worked fine in a past VB.NET project.

13条回答
▲ chillily
2楼-- · 2019-01-04 06:11

It sounds like this.Opacity is a double value, and the compiler doesn't like you trying to cram a decimal value into it.

查看更多
等我变得足够好
3楼-- · 2019-01-04 06:13
this.Opacity = trackBar1.Value / 5000d;
查看更多
可以哭但决不认输i
4楼-- · 2019-01-04 06:16

Since Opacity is a double value, I would just use a double from the outset and not cast at all, but be sure to use a double when dividing so you don't loose any precision

Opacity = trackBar1.Value / 5000.0;
查看更多
Root(大扎)
5楼-- · 2019-01-04 06:17

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.

查看更多
仙女界的扛把子
6楼-- · 2019-01-04 06:17

In my opinion, it is desirable to be as explicit as possible. This adds clarity to the code and aids your fellow programmers who may eventually read it.

In addition to (or instead of) appending a .0 to the number, you can use decimal.ToDouble().

Here are some examples:

// Example 1
double transperancy = trackBar1.Value/5000;
this.Opacity = decimal.ToDouble(transperancy);

// Example 2 - with inline temp
this.Opacity = decimal.ToDouble(trackBar1.Value/5000);
查看更多
何必那么认真
7楼-- · 2019-01-04 06:17

You should use 5000.0 instead of 5000.

查看更多
登录 后发表回答