While applying opacity to a form, should we use a decimal or a double value?

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.


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;

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


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.

链接地址: http://www.djcxy.com/p/15802.html

上一篇: 在身上设置的CSS3渐变背景不会伸展,而是重复?

下一篇: 在将不透明度应用于表单时,我们应该使用小数还是双精度值?