programing

Decimal을 Double로 변환

nasanasas 2020. 10. 2. 22:30
반응형

Decimal을 Double로 변환


트랙 바를 사용하여 양식의 불투명도를 변경하고 싶습니다.

이것은 내 코드입니다.

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

애플리케이션을 빌드 할 때 다음 오류가 발생합니다.

암시 적으로 형식 decimal을 다음으로 변환 할 수 없습니다.double

나는 사용하여 시도 trans하고 double그러나 컨트롤이 작동하지 않습니다. 이 코드는 과거 VB.NET 프로젝트에서 잘 작동했습니다.


다음과 같이 double로 명시 적으로 캐스트 할 필요가 없습니다.

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

상수를로 5000.0(또는로 5000d) 식별하는 것으로 충분합니다.

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

일반적인 질문 "Decimal vs Double?"에 대한보다 일반적인 대답 : 정밀도를 유지하기위한 화폐 계산의 경우 Decimal , 작은 차이의 영향을받지 않는 과학적 계산의 경우 Double . Double은 CPU에 고유 한 유형이므로 (내부 표현은 base 2에 저장 됨 ) Double로 만든 계산은 Decimal ( 내부적으로 10 진수로 표시됨)보다 성능이 더 좋습니다 .


코드는 암시 적으로 모든 캐스트를 수행하기 때문에 VB.NET에서 제대로 작동했지만 C #에는 암시 적 및 명시 적 캐스트가 모두 있습니다.

C #에서는 정확도를 잃기 때문에 십진수에서 두 배로의 변환이 명시 적입니다. 예를 들어 1.1은 double로 정확하게 표현할 수 없지만 10 진수로 표현할 수 있습니다 ( 이유에 대해서는 " 부동 소수점 숫자-생각보다 정확하지 않음"참조).

VB에서는 컴파일러에 의해 변환이 추가되었습니다.

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

이는 (double)C #에서 명시 적으로 명시해야하지만 VB의 '관용'컴파일러에 의해 암시 될 수 있습니다 .


5000으로 나누는 이유는 무엇입니까? TrackBar의 최소값과 최대 값을 0에서 100 사이로 설정 한 다음 불투명도 백분율에 대해 값을 100으로 나눕니다. 아래의 최소 20 개의 예는 양식이 완전히 보이지 않도록 방지합니다.

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

두 가지 문제가 있습니다. 첫째, Opacity10 진수 값이 아닌 double이 필요합니다. 컴파일러는 decimal과 double 사이에 변환이 있지만 작동하기 위해 지정해야하는 명시 적 변환이라고 알려줍니다. 두 번째는 TrackBar.Value정수 값이며 int를 int로 나누면 어떤 유형의 변수에 할당하더라도 int가됩니다. 이 경우 int에서 decimal 또는 double 로의 암시 적 캐스트가 있습니다. 캐스트를 수행 할 때 정밀도의 손실이 없기 때문에 컴파일러는 불평하지 않지만 얻을 수있는 값은 항상 0입니다.trackBar.Value이 솔루션은 두 배 (불투명도에 대한 기본 유형)를 사용하는 코드를 변경하고 명시 적으로 이중 상수를하여 부동 소수점 연산 않는 적은 5000보다 항상 - 또는 주조 - 산술 증진의 효과가되는 trackBar.Value두 배를 , 동일한 작업 또는 둘 다를 수행합니다. 아, 그리고 다른 곳에서 사용하지 않는 한 중간 변수가 필요하지 않습니다. 내 생각 엔 컴파일러가 어쨌든 그것을 최적화 할 것입니다.

trackBar.Opacity = (double)trackBar.Value / 5000.0;

제 생각에는 가능한 한 명시적인 것이 바람직합니다. 이것은 코드에 명확성을 추가하고 결국 그것을 읽을 수있는 동료 프로그래머에게 도움이됩니다.

.0숫자에 a 추가 (또는 대신)하는 것 외에도 decimal.ToDouble().

여기 몇 가지 예가 있어요.

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

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

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


You should use 5000.0 instead of 5000.


The Opacity property is of double type:

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

or simply:

this.Opacity = trackBar1.Value / 5000.0;

or:

this.Opacity = trackBar1.Value / 5000d;

Notice that I am using 5000.0 (or 5000d) to force a double division because trackBar1.Value is an integer and it would perform an integer division and the result would be an integer.


Assuming you are using WinForms, Form.Opacity is of type double, so you should use:

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

Unless you need the value elsewhere, it's simpler to write:

this.Opacity = trackBar1.Value / 5000.0;

The reason the control doesn't work when you changed your code to simply be a double was because you had:

double trans = trackbar1.Value / 5000;

which interpreted the 5000 as an integer, and because trackbar1.Value is also an integer your trans value was always zero. By explicitly making the numeric a floating point value by adding the .0 the compiler can now interpret it as a double and perform the proper calculation.


The best solution is:

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

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;

this.Opacity = trackBar1.Value / 5000d;

참고URL : https://stackoverflow.com/questions/4/convert-decimal-to-double

반응형