Transform Decimal to Double?

I intend to make use of a track-bar to transform a kind's opacity.

This is my code:

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

When I construct the application, it offers the adhering to mistake:

Can not unconditionally transform type 'decimal' to 'double'.

I attempted making use of trans and also double yet after that the control does not function. This code functioned penalty in a previous VB.NET task.

2019-05-06 23:57:56
Source Share
Answers: 5

Your code functioned penalty in VB.NET due to the fact that it unconditionally does any kind of casts, while C# has both implied and also specific ones.

In C# the conversion from decimal to double is specific as you shed precision. As an example 1.1 can not be properly shared as a double, yet can as a decimal (see "Floating point numbers - more inaccurate than you think" for the reason that).

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

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

That (double) needs to be clearly mentioned in C#, yet can be indicated by VB is extra 'forgiving' compiler.

2019-05-19 21:22:20

In my point of view, it is preferable to be as specific as feasible. This includes quality to the code and also help your other designers that might at some point read it.

Along with (or as opposed to) adding a .0 to the number, you can make use of decimal.ToDouble().

Below are some instances :

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

// Example 2 - with inline temp
this.Opacity = decimal.ToDouble(trackBar1.Value/5000);
2019-05-10 11:17:50

It seems like this.Opacity is a double value, and also the compiler does not like you attempting to pack a decimal value right into it.

2019-05-08 20:28:24

An extra common solution for the common inquiry "Decimal vs Double?" : Decimal for financial estimations to maintain the accuracy, Double for clinical estimations that do not get influenced by tiny distinctions. Given that Double is a type which is belonging to the CPU (inner depiction is saved in base 2 ), estimations made with Double execute far better after that Decimal (which is stood for in base 10 inside).

2019-05-08 20:10:02

A specific actors to double similar to this isn't essential :

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

Identifying the constant as 5000.0 (or as 5000d) suffices :

double trans = trackBar1.Value / 5000.0;
double trans = trackBar1.Value / 5000d;
2019-05-08 19:44:56