将十进制转换为双倍？

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

15 个答案:

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

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

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

``````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;
}
``````

``trackBar.Value``

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

// Example 2 - with inline temp
this.Opacity = decimal.ToDouble(trackBar1.Value/5000);
``````

Opacity属性是双重类型：

``````double trans = trackBar1.Value / 5000.0;
this.Opacity = trans;
``````

``````this.Opacity = trackBar1.Value / 5000.0;
``````

``````this.Opacity = trackBar1.Value / 5000d;
``````

``````double trans = trackBar1.Value / 5000.0;
this.Opacity = trans;
``````

``````this.Opacity = trackBar1.Value / 5000.0;
``````

``````double trans = trackbar1.Value / 5000;
``````

`5000`解释为整数，并且因为`trackbar1.Value`也是一个整数，所以`trans`值始终为零。通过添加`.0`显式地使数字成为浮点值，编译器现在可以将其解释为double并执行正确的计算。

``````Opacity = trackBar1.Value / 5000.0;
``````

``````this.Opacity = decimal.ToDouble(trackBar1.Value/5000);
``````

``````this.Opacity = trackBar1.Value / 5000d;
``````

``````this.Opacity = decimal.ToDouble(trackBar1.Value / 5000.0);
``````

``````double trans = trackBar1.Value / 5000.0;
this.Opacity = trans;
``````

``````this.Opacity = trackBar1.Value / 5000.0;
``````

``````double trans = trackBar1.Value / 5000.0;
this.Opacity = Decimal.ToDouble(trans);
``````