System.Double 구조체

비고

이 문서는 이 API에 대한 참조 설명서를 보충하는 추가 설명을 제공합니다.

값 형식은 Double 음수 1.79769313486232e308에서 양수 1.79769313486232e308까지, 양수 또는 음수 0, PositiveInfinity, NegativeInfinity, 그리고 숫자가 아님(NaN)을 포함한 배정밀도 64비트 숫자를 나타냅니다. 매우 크거나(예: 행성이나 은하 사이의 거리) 또는 매우 작은 값(예: 킬로그램 단위의 물질의 분자 질량)을 나타내기 위한 것이며 종종 부정확합니다(예: 지구에서 다른 태양계까지의 거리). Double 형식은 이진 부동 소수점 산술 연산에 대한 IEC 60559:1989(IEEE 754) 표준을 준수합니다.

부동 소수점 표현 및 정밀도

데이터 형식은 Double 다음 표와 같이 배정밀도 부동 소수점 값을 64비트 이진 형식으로 저장합니다.

부분 비트
가수(Significand) 또는 맨티사(mantissa) 0-51
지수 52-62
기호(0 = 양수, 1 = 음수) 63

소수 자릿수가 일부 분수 값(예: 1/3 또는 Math.PI)을 정확하게 나타낼 수 없는 것처럼 이진 분수는 일부 소수 값을 나타낼 수 없습니다. 예를 들어 .1로 정확하게 10진수로 표현되는 1/10은 .001100110011 이진 분수로 표현되며 패턴 "0011"은 무한대로 반복됩니다. 이 경우 부동 소수점 값은 나타내는 숫자의 부정확한 표현을 제공합니다. 원래 부동 소수점 값에 대해 추가 수학 연산을 수행하면 정밀도가 부족한 경우가 많습니다. 예를 들어 .1을 10으로 곱하고 .1을 .1에서 .1로 9번 추가한 결과를 비교하면 8개의 작업이 더 포함되었기 때문에 정확도가 낮은 결과가 생성되었음을 알 수 있습니다. .NET 10 이전에는 두 개의 Double 값을 "R" 표준 숫자 형식 문자열을 사용하여 표시할 때, Double 형식이 지원하는 최대 17자리의 ~전체~ 자릿수 정확도가 드러나면서 이러한 차이가 분명해집니다.

using System;

public class Example13
{
    public static void Main()
    {
        Double value = .1;
        Double result1 = value * 10;
        Double result2 = 0;
        for (int ctr = 1; ctr <= 10; ctr++)
            result2 += value;

        Console.WriteLine($".1 * 10:           {result1:R}");
        Console.WriteLine($".1 Added 10 times: {result2:R}");
    }
}
// The example displays the following output:
//       .1 * 10:           1
//       .1 Added 10 times: 0.99999999999999989
let value = 0.1
let result1 = value * 10.
let mutable result2 = 0.
for i = 1 to 10 do
    result2 <- result2 + value

printfn $".1 * 10:           {result1:R}"
printfn $".1 Added 10 times: {result2:R}"
// The example displays the following output:
//       .1 * 10:           1
//       .1 Added 10 times: 0.99999999999999989
Module Example14
    Public Sub Main()
        Dim value As Double = 0.1
        Dim result1 As Double = value * 10
        Dim result2 As Double
        For ctr As Integer = 1 To 10
            result2 += value
        Next
        Console.WriteLine(".1 * 10:           {0:R}", result1)
        Console.WriteLine(".1 Added 10 times: {0:R}", result2)
    End Sub
End Module
' The example displays the following output:
'       .1 * 10:           1
'       .1 Added 10 times: 0.99999999999999989

일부 숫자는 소수점 이진 값으로 정확하게 나타낼 수 없으므로 부동 소수점 숫자는 실제 숫자와 근사치일 수 있습니다.

또한 모든 부동 소수점 숫자에는 제한된 수의 유효 자릿수가 있으며, 이는 부동 소수점 값이 실제 숫자와 근사치를 얼마나 정확하게 나타내는지도 결정합니다. Double 값의 전체 자릿수는 15자리이지만 내부적으로는 최대 17자리 자릿수가 유지됩니다. 즉, 일부 부동 소수점 연산에는 부동 소수점 값을 변경할 정밀도가 부족할 수 있습니다. 다음 예제에서 이에 대해 설명합니다. 매우 큰 부동 소수점 값을 정의한 다음, Double.Epsilon과 천조의 곱을 그것에 추가합니다. 그러나 제품이 너무 작아서 원래 부동 소수점 값을 수정할 수 없습니다. 가장 낮은 유효 자릿수는 천 번째인 반면 제품에서 가장 중요한 숫자는 10-309입니다.

using System;

public class Example14
{
    public static void Main()
    {
        Double value = 123456789012.34567;
        Double additional = Double.Epsilon * 1e15;
        Console.WriteLine($"{value} + {additional} = {value + additional}");
    }
}
// The example displays the following output:
//    123456789012.346 + 4.94065645841247E-309 = 123456789012.346
open System

let value = 123456789012.34567
let additional = Double.Epsilon * 1e15
printfn $"{value} + {additional} = {value + additional}"
// The example displays the following output:
//    123456789012.346 + 4.94065645841247E-309 = 123456789012.346
Module Example15
    Public Sub Main()
        Dim value As Double = 123456789012.34567
        Dim additional As Double = Double.Epsilon * 1.0E+15
        Console.WriteLine("{0} + {1} = {2}", value, additional,
                                           value + additional)
    End Sub
End Module
' The example displays the following output:
'   123456789012.346 + 4.94065645841247E-309 = 123456789012.346

부동 소수점 숫자의 제한된 정밀도에는 다음과 같은 몇 가지 결과가 있습니다.

  • 특정 정밀도에서는 동일하게 보이는 두 부동소수점 숫자가 가장 낮은 자리 숫자가 다르기 때문에 서로 같지 않을 수 있습니다. 다음 예제에서는 일련의 숫자가 함께 추가되고 해당 합계가 예상 합계와 비교됩니다.

    using System;
    
    public class Example10
    {
        public static void Main()
        {
            Double[] values = { 10.0, 2.88, 2.88, 2.88, 9.0 };
            Double result = 27.64;
            Double total = 0;
            foreach (var value in values)
                total += value;
    
            if (total.Equals(result))
                Console.WriteLine("The sum of the values equals the total.");
            else
                Console.WriteLine($"The sum of the values ({total}) does not equal the total ({result}).");
        }
    }
    // The example displays the following output:
    //      The sum of the values (36.64) does not equal the total (36.64).
    //
    // If the index items in the Console.WriteLine statement are changed to {0:R},
    // the example displays the following output:
    //       The sum of the values (27.639999999999997) does not equal the total (27.64).
    
    let values = [ 10.0; 2.88; 2.88; 2.88; 9.0 ]
    let result = 27.64
    let total = List.sum values
    
    if total.Equals result then
        printfn "The sum of the values equals the total."
    else
        printfn $"The sum of the values ({total}) does not equal the total ({result})."
    // The example displays the following output:
    //      The sum of the values (36.64) does not equal the total (36.64).
    //
    // If the index items in the Console.WriteLine statement are changed to {0:R},
    // the example displays the following output:
    //       The sum of the values (27.639999999999997) does not equal the total (27.64).
    
    Module Example11
        Public Sub Main()
            Dim values() As Double = {10.0, 2.88, 2.88, 2.88, 9.0}
            Dim result As Double = 27.64
            Dim total As Double
            For Each value In values
                total += value
            Next
            If total.Equals(result) Then
                Console.WriteLine("The sum of the values equals the total.")
            Else
                Console.WriteLine("The sum of the values ({0}) does not equal the total ({1}).",
                               total, result)
            End If
        End Sub
    End Module
    ' The example displays the following output:
    '      The sum of the values (36.64) does not equal the total (36.64).   
    '
    ' If the index items in the Console.WriteLine statement are changed to {0:R},
    ' the example displays the following output:
    '       The sum of the values (27.639999999999997) does not equal the total (27.64).
    

    두 값은 더하기 작업 중에 정밀도가 손실되어 같지 않습니다. 이 경우 비교를 수행하기 전에 Math.Round(Double, Int32) 메서드를 호출하여 Double 값을 원하는 전체 자릿수로 반올림하여 문제를 해결할 수 있습니다.

  • 부동 소수점 숫자를 사용하는 수학 또는 비교 연산은 이진 부동 소수점 숫자가 10진수와 같지 않을 수 있으므로 소수점 숫자를 사용하는 경우 동일한 결과를 생성하지 못할 수 있습니다. 이전 예제에서는 .1을 10으로 곱하고 .1을 곱한 결과를 표시하여 이를 설명했습니다.

    소수점 값을 가진 숫자 연산의 정확도가 중요한 경우 Decimal 형식을 사용하고 Double 형식은 사용하지 않는 것이 좋습니다. 정수 값이 형식 범위를 초과하는 숫자 연산의 Int128UInt128 정확도가 중요한 경우 형식을 BigInteger 사용합니다.

  • 부동 소수점 숫자가 포함된 경우 값이 왕복 않을 수 있습니다. 연산이 원래의 부동 소수점 숫자를 다른 형태로 변환하고, 역연산이 그 변환된 형태를 다시 부동 소수점 숫자로 변환하며, 최종 부동 소수점 숫자가 원래의 부동 소수점 숫자와 같다면, 이러한 과정을 왕복 과정이라고 합니다. 변환에서 하나 이상의 유효 자릿수가 손실되거나 변경되어 왕복이 실패할 수 있습니다.

    다음 예제에서는 세 Double 값이 문자열로 변환되고 파일에 저장됩니다. .NET Framework에서 이 예제를 실행하면 값이 동일한 것처럼 보이지만 복원된 값은 원래 값과 같지 않습니다. 이후 .NET에서 값이 정확하게 왕복되도록 이 문제를 해결했습니다.

    StreamWriter sw = new(@"./Doubles.dat");
    double[] values = [2.2 / 1.01, 1.0 / 3, Math.PI];
    for (int ctr = 0; ctr < values.Length; ctr++)
    {
        sw.Write(values[ctr].ToString());
        if (ctr != values.Length - 1)
            sw.Write("|");
    }
    sw.Close();
    
    double[] restoredValues = new double[values.Length];
    StreamReader sr = new(@"./Doubles.dat");
    string temp = sr.ReadToEnd();
    string[] tempStrings = temp.Split('|');
    for (int ctr = 0; ctr < tempStrings.Length; ctr++)
        restoredValues[ctr] = double.Parse(tempStrings[ctr]);
    
    for (int ctr = 0; ctr < values.Length; ctr++)
    Console.WriteLine($"{values[ctr]} {(values[ctr].Equals(restoredValues[ctr]) ? "=" : "<>")} {restoredValues[ctr]}");
    
    // For .NET Framework only, the example displays the following output:
    //       2.17821782178218 <> 2.17821782178218
    //       0.333333333333333 <> 0.333333333333333
    //       3.14159265358979 <> 3.14159265358979
    
    open System
    open System.IO
    
    let values = [ 2.2 / 1.01; 1. / 3.; Math.PI ]
    
    using (new StreamWriter(@".\Doubles.dat")) (fun sw ->
        for i = 0 to values.Length - 1 do
            sw.Write(string values[i])
            if i <> values.Length - 1 then
                sw.Write "|")
    
    using (new StreamReader(@".\Doubles.dat")) (fun sr ->
        let temp = sr.ReadToEnd()
        let tempStrings = temp.Split '|'
    
        let restoredValues =
            [ for i = 0 to tempStrings.Length - 1 do
                  Double.Parse tempStrings[i] ]
    
        for i = 0 to values.Length - 1 do
            printfn $"""{values[i]} {if values[ i ].Equals restoredValues[i] then "=" else "<>"} {restoredValues[i]}""")
    
    // The example displays the following output:
    //       2.17821782178218 <> 2.17821782178218
    //       0.333333333333333 <> 0.333333333333333
    //       3.14159265358979 <> 3.14159265358979
    
    Imports System.IO
    
    Module Example12
        Public Sub Main()
            Dim sw As New StreamWriter(".\Doubles.dat")
            Dim values() As Double = {2.2 / 1.01, 1.0 / 3, Math.PI}
            For ctr As Integer = 0 To values.Length - 1
                sw.Write(values(ctr).ToString())
                If ctr <> values.Length - 1 Then sw.Write("|")
            Next
            sw.Close()
    
            Dim restoredValues(values.Length - 1) As Double
            Dim sr As New StreamReader(".\Doubles.dat")
            Dim temp As String = sr.ReadToEnd()
            Dim tempStrings() As String = temp.Split("|"c)
            For ctr As Integer = 0 To tempStrings.Length - 1
                restoredValues(ctr) = Double.Parse(tempStrings(ctr))
            Next
    
            For ctr As Integer = 0 To values.Length - 1
                Console.WriteLine("{0} {2} {1}", values(ctr),
                               restoredValues(ctr),
                               If(values(ctr).Equals(restoredValues(ctr)), "=", "<>"))
            Next
        End Sub
    End Module
    ' The example displays the following output:
    '       2.17821782178218 <> 2.17821782178218
    '       0.333333333333333 <> 0.333333333333333
    '       3.14159265358979 <> 3.14159265358979
    

    .NET Framework를 대상으로 하는 경우 "G17" 표준 숫자 형식 문자열을 사용하여 Double 값의 전체 자릿수를 유지함으로써 성공적으로 라운드트립할 수 있습니다.

  • Single 값은 Double 값보다 정밀도가 낮습니다. Single 값이 표면상 동등한 Double 값으로 변환되더라도, 정밀도의 차이로 인해 Double 값과 동일하지 않은 경우가 많습니다. 다음 예제에서는 동일한 나누기 작업의 결과가 a DoubleSingle 값에 할당됩니다. Single 값이 Double캐스팅된 후 두 값을 비교하면 같지 않음이 표시됩니다.

    using System;
    
    public class Example9
    {
        public static void Main()
        {
            Double value1 = 1 / 3.0;
            Single sValue2 = 1 / 3.0f;
            Double value2 = (Double)sValue2;
            Console.WriteLine($"{value1:R} = {value2:R}: {value1.Equals(value2)}");
        }
    }
    // The example displays the following output:
    //        0.33333333333333331 = 0.3333333432674408: False
    
    open System
    
    let value1 = 1. / 3.
    let sValue2 = 1f /3f
    
    let value2 = double sValue2
    printfn $"{value1:R} = {value2:R}: {value1.Equals value2}"
    // The example displays the following output:
    //        0.33333333333333331 = 0.3333333432674408: False
    
    Module Example10
        Public Sub Main()
            Dim value1 As Double = 1 / 3
            Dim sValue2 As Single = 1 / 3
            Dim value2 As Double = CDbl(sValue2)
            Console.WriteLine("{0} = {1}: {2}", value1, value2, value1.Equals(value2))
        End Sub
    End Module
    ' The example displays the following output:
    '       0.33333333333333331 = 0.3333333432674408: False
    

    이 문제를 방지하려면 Double를 데이터 형식 Single 대신 사용하거나, 두 값의 정확도가 같아지도록 Round 메서드를 사용하십시오.

또한 Double 값을 사용한 산술 및 할당 연산의 결과는 Double 유형의 정밀도 손실로 인해 플랫폼에 따라 다소 차이가 있을 수 있습니다. 예를 들어 리터럴 Double 값을 할당한 결과는 32비트 및 64비트 버전의 .NET 다를 수 있습니다. 다음 예제에서는 리터럴 값 -4.423306042444772E-305와 값이 -4.423306042444772E-305인 변수가 변수에 Double 할당된 경우의 이 차이를 보여 줍니다. 이 경우 Parse(String) 메서드의 결과는 정밀도 손실이 없습니다.

double value = -4.42330604244772E-305;

double fromLiteral = -4.42330604244772E-305;
double fromVariable = value;
double fromParse = Double.Parse("-4.42330604244772E-305");

Console.WriteLine("Double value from literal: {0,29:R}", fromLiteral);
Console.WriteLine("Double value from variable: {0,28:R}", fromVariable);
Console.WriteLine("Double value from Parse method: {0,24:R}", fromParse);
// On 32-bit versions of the .NET Framework, the output is:
//    Double value from literal:        -4.42330604244772E-305
//    Double value from variable:       -4.42330604244772E-305
//    Double value from Parse method:   -4.42330604244772E-305
//
// On other versions of the .NET Framework, the output is:
//    Double value from literal:      -4.4233060424477198E-305
//    Double value from variable:     -4.4233060424477198E-305
//    Double value from Parse method:   -4.42330604244772E-305
let value = -4.42330604244772E-305

let fromLiteral = -4.42330604244772E-305
let fromVariable = value
let fromParse = Double.Parse "-4.42330604244772E-305"

printfn $"Double value from literal: {fromLiteral,29:R}"
printfn $"Double value from variable: {fromVariable,28:R}"
printfn $"Double value from Parse method: {fromParse,24:R}"
// On 32-bit versions of the .NET Framework, the output is:
//    Double value from literal:        -4.42330604244772E-305
//    Double value from variable:       -4.42330604244772E-305
//    Double value from Parse method:   -4.42330604244772E-305
//
// On other versions of the .NET Framework, the output is:
//    Double value from literal:      -4.4233060424477198E-305
//    Double value from variable:     -4.4233060424477198E-305
//    Double value from Parse method:   -4.42330604244772E-305
Dim value As Double = -4.4233060424477198E-305

Dim fromLiteral As Double = -4.4233060424477198E-305
Dim fromVariable As Double = value
Dim fromParse As Double = Double.Parse("-4.42330604244772E-305")

Console.WriteLine("Double value from literal: {0,29:R}", fromLiteral)
Console.WriteLine("Double value from variable: {0,28:R}", fromVariable)
Console.WriteLine("Double value from Parse method: {0,24:R}", fromParse)
' On 32-bit versions of the .NET Framework, the output is:
'    Double value from literal:        -4.42330604244772E-305
'    Double value from variable:       -4.42330604244772E-305
'    Double value from Parse method:   -4.42330604244772E-305
'
' On other versions of the .NET Framework, the output is:
'    Double value from literal:        -4.4233060424477198E-305
'    Double value from variable:       -4.4233060424477198E-305
'    Double value from Parse method:     -4.42330604244772E-305

동등성 테스트

같게 간주하려면 두 Double 값이 동일한 값을 나타내야 합니다. 그러나 값 간의 정밀도 차이 또는 하나 또는 두 값 모두에 의한 정밀도 손실로 인해 동일할 것으로 예상되는 부동 소수점 값은 가장 낮은 유효 자릿수의 차이로 인해 같지 않은 것으로 판명되는 경우가 많습니다. 따라서 두 값이 같은지 여부를 확인하기 위해 Equals 메서드를 호출하거나 두 CompareTo 값 간의 관계를 확인하기 위해 Double 메서드를 호출하면 예기치 않은 결과가 발생하는 경우가 많습니다. 이는 다음 예제에서 분명하게 알 수 있습니다. 첫 번째 값은 15자리의 정밀도를 가지고 두 번째 값은 17자리이므로 동일한 두 Double 값이 같지 않은 것으로 판명됩니다.

using System;

public class Example
{
   public static void Main()
   {
      double value1 = .333333333333333;
      double value2 = 1.0/3;
      Console.WriteLine($"{value1} = {value2}: {value1.Equals(value2)}");
   }
}
// The example displays the following output:
//        0.333333333333333 = 0.33333333333333331: False
open System

let value1 = 0.333333333333333
let value2 = 1. / 3.
printfn $"{value1} = {value2}: {value1.Equals value2}"

// The example displays the following output:
//        0.333333333333333 = 0.33333333333333331: False
Module Example1
    Public Sub Main()
        Dim value1 As Double = 0.333333333333333
        Dim value2 As Double = 1 / 3
        Console.WriteLine("{0} = {1}: {2}", value1, value2, value1.Equals(value2))
    End Sub
End Module

' The example displays the following output:
'       0.333333333333333 = 0.33333333333333331: False

정밀도 손실이 비교 결과에 영향을 미칠 가능성이 있는 경우, Equals 또는 CompareTo 메서드를 호출하는 대신 다음 대안 중 하나를 채택할 수 있습니다.

  • Math.Round 메서드를 호출하여 두 값의 정밀도가 같은지 확인합니다. 다음 예제에서는 두 개의 소수 값이 동일하도록 이 방법을 사용하도록 이전 예제를 수정합니다.

    double value1 = .333333333333333;
    double value2 = 1.0 / 3;
    int precision = 7;
    value1 = Math.Round(value1, precision);
    value2 = Math.Round(value2, precision);
    Console.WriteLine($"{value1} = {value2}: {value1.Equals(value2)}");
    
    // The example displays the following output:
    //        0.3333333 = 0.3333333: True
    
    open System
    
    let v1 = 0.333333333333333
    let v2 = 1. / 3.
    let precision = 7
    let value1 = Math.Round(v1, precision)
    let value2 = Math.Round(v2, precision)
    printfn $"{value1} = {value2}: {value1.Equals value2}"
    
    // The example displays the following output:
    //        0.3333333 = 0.3333333: True
    
    Module Example3
        Public Sub Main()
            Dim value1 As Double = 0.333333333333333
            Dim value2 As Double = 1 / 3
            Dim precision As Integer = 7
            value1 = Math.Round(value1, precision)
            value2 = Math.Round(value2, precision)
            Console.WriteLine("{0} = {1}: {2}", value1, value2, value1.Equals(value2))
        End Sub
    End Module
    
    ' The example displays the following output:
    '       0.3333333 = 0.3333333: True
    

    정밀도 문제는 여전히 중간점 값의 반올림에 적용됩니다. 자세한 내용은 Math.Round(Double, Int32, MidpointRounding) 메서드를 참조하세요.

  • 정확한 같음이 아닌 대략적인 같음을 테스트합니다. 이렇게 하려면 두 값이 다를 수 있지만 여전히 같을 수 있는 절대 크기를 정의하거나 더 작은 값이 더 큰 값과 다를 수 있는 상대 크기를 정의해야 합니다.

    경고

    Double.Epsilon 같음을 테스트할 때 두 Double 값 사이의 거리를 절대 측정값으로 사용하는 경우가 있습니다. 그러나 Double.Epsilon는 값이 0인 Double에 더하거나 뺄 수 있는 가능한 가장 작은 값을 측정합니다. 대부분의 양수 및 음수 Double 값의 경우 Double.Epsilon 값이 너무 작아 검색할 수 없습니다. 따라서 0인 값을 제외하고 같음 테스트에는 사용하지 않는 것이 좋습니다.

    다음 예제에서는 후자의 방법을 사용하여 두 값 간의 상대적 차이를 테스트하는 IsApproximatelyEqual 메서드를 정의합니다. 이 메서드는 Math.Max(value1, value2)으로 나누어 두 값 중 절대값이 더 큰 값을 기준으로 상대적으로 비교하여, 결과가 올바른 크기의 순서에 놓이도록 합니다. 값 중 하나가 0이고 다른 하나가 음수인 경우 Math.Max가 0을 반환하면, 메서드는 Math.Min(value1, value2)로 대체되어 0이 아닌 값을 제수로 사용합니다. 또한 IsApproximatelyEqual 메서드 및 Equals(Double) 메서드에 대한 호출의 결과와 대조됩니다.

    using System;
    
    public class Example3
    {
        public static void Main()
        {
            double one1 = .1 * 10;
            double one2 = 0;
            for (int ctr = 1; ctr <= 10; ctr++)
                one2 += .1;
    
            Console.WriteLine($"{one1} = {one2}: {one1.Equals(one2)}");
            Console.WriteLine($"{one1} is approximately equal to {one2}: {IsApproximatelyEqual(one1, one2, .000000001)}");
        }
    
        static bool IsApproximatelyEqual(double value1, double value2, double epsilon)
        {
            // If they are equal anyway, just return True.
            if (value1.Equals(value2))
                return true;
    
            // Handle NaN, Infinity.
            if (Double.IsInfinity(value1) | Double.IsNaN(value1))
                return value1.Equals(value2);
            else if (Double.IsInfinity(value2) | Double.IsNaN(value2))
                return value1.Equals(value2);
    
            // Handle zero to avoid division by zero
            double divisor = Math.Max(value1, value2);
            if (divisor.Equals(0))
                divisor = Math.Min(value1, value2);
    
            return Math.Abs((value1 - value2) / divisor) <= epsilon;
        }
    }
    
    // The example displays the following output:
    //       1 = 0.99999999999999989: False
    //       1 is approximately equal to 0.99999999999999989: True
    
    open System
    
    let isApproximatelyEqual (value1: double) (value2: double) (epsilon: double) =
        // If they are equal anyway, just return True.
        if value1.Equals value2 then
            true
        else
            // Handle NaN, Infinity.
            if Double.IsInfinity value1 || Double.IsNaN value1 then
                value1.Equals value2
            elif Double.IsInfinity value2 || Double.IsNaN value2 then
                value1.Equals value2
            else
                // Handle zero to avoid division by zero
                let divisor = max value1 value2
                let divisor =
                    if divisor.Equals 0 then
                        min value1 value2
                    else
                        divisor
                abs ((value1 - value2) / divisor) <= epsilon
    
    let one1 = 0.1 * 10.
    let mutable one2 = 0.
    for _ = 1 to 10 do
        one2 <- one2 + 0.1
    
    printfn $"{one1} = {one2}: {one1.Equals one2}"
    printfn $"{one1} is approximately equal to {one2}: {isApproximatelyEqual one1 one2 0.000000001}"
    
    // The example displays the following output:
    //       1 = 0.99999999999999989: False
    //       1 is approximately equal to 0.99999999999999989: True
    
    Module Example4
        Public Sub Main()
            Dim one1 As Double = 0.1 * 10
            Dim one2 As Double = 0
            For ctr As Integer = 1 To 10
                one2 += 0.1
            Next
            Console.WriteLine("{0} = {1}: {2}", one1, one2, one1.Equals(one2))
            Console.WriteLine("{0} is approximately equal to {1}: {2}",
                            one1, one2,
                            IsApproximatelyEqual(one1, one2, 0.000000001))
        End Sub
    
        Function IsApproximatelyEqual(value1 As Double, value2 As Double,
                                     epsilon As Double) As Boolean
            ' If they are equal anyway, just return True.
            If value1.Equals(value2) Then Return True
    
            ' Handle NaN, Infinity.
            If Double.IsInfinity(value1) Or Double.IsNaN(value1) Then
                Return value1.Equals(value2)
            ElseIf Double.IsInfinity(value2) Or Double.IsNaN(value2) Then
                Return value1.Equals(value2)
            End If
    
            ' Handle zero to avoid division by zero
            Dim divisor As Double = Math.Max(value1, value2)
            If divisor.Equals(0) Then
                divisor = Math.Min(value1, value2)
            End If
    
            Return Math.Abs((value1 - value2) / divisor) <= epsilon
        End Function
    End Module
    
    ' The example displays the following output:
    '       1 = 0.99999999999999989: False
    '       1 is approximately equal to 0.99999999999999989: True
    

부동 소수점 값 및 예외

정수 계열 형식의 연산은 0으로 나눌 때 DivideByZeroException 예외를, 오버플로 시 OverflowException 예외를 검사된 컨텍스트에서 throw하는 것과 달리, 부동 소수점 값과 관련된 연산은 예외를 throw하지 않습니다. 대신 예외적인 상황에서 부동 소수점 연산의 결과는 0, 양수 무한대, 음의 무한대 또는 숫자(NaN)가 아닙니다.

  • 부동 소수점 연산의 결과가 대상 형식에 비해 너무 작으면 결과는 0입니다. 이 문제는 다음 예제와 같이 두 개의 매우 작은 숫자를 곱할 때 발생할 수 있습니다.

    using System;
    
    public class Example6
    {
        public static void Main()
        {
            Double value1 = 1.1632875981534209e-225;
            Double value2 = 9.1642346778e-175;
            Double result = value1 * value2;
            Console.WriteLine($"{value1} * {value2} = {result}");
            Console.WriteLine($"{result} = 0: {result.Equals(0.0)}");
        }
    }
    // The example displays the following output:
    //       1.16328759815342E-225 * 9.1642346778E-175 = 0
    //       0 = 0: True
    
    let value1 = 1.1632875981534209e-225
    let value2 = 9.1642346778e-175
    let result = value1 * value2
    printfn $"{value1} * {value2} = {result}"
    printfn $"{result} = 0: {result.Equals 0.0}"
    // The example displays the following output:
    //       1.16328759815342E-225 * 9.1642346778E-175 = 0
    //       0 = 0: True
    
    Module Example7
        Public Sub Main()
            Dim value1 As Double = 1.1632875981534209E-225
            Dim value2 As Double = 9.1642346778E-175
            Dim result As Double = value1 * value2
            Console.WriteLine("{0} * {1} = {2}", value1, value2, result)
            Console.WriteLine("{0} = 0: {1}", result, result.Equals(0.0))
        End Sub
    End Module
    ' The example displays the following output:
    '       1.16328759815342E-225 * 9.1642346778E-175 = 0
    '       0 = 0: True
    
  • 부동 소수점 연산 결과의 크기가 대상 형식의 범위를 초과하는 경우, 결과의 부호에 따라 연산의 결과는 PositiveInfinity 또는 NegativeInfinity이 됩니다. 어떤 작업이 Double.MaxValue에서 오버플로하면 그 결과는 PositiveInfinity이고, Double.MinValue에서 오버플로하는 작업의 결과는 NegativeInfinity입니다. 이는 다음 예제에서 볼 수 있습니다.

    using System;
    
    public class Example7
    {
        public static void Main()
        {
            Double value1 = 4.565e153;
            Double value2 = 6.9375e172;
            Double result = value1 * value2;
            Console.WriteLine($"PositiveInfinity: {Double.IsPositiveInfinity(result)}");
            Console.WriteLine($"NegativeInfinity: {Double.IsNegativeInfinity(result)}{Environment.NewLine}");
    
            value1 = -value1;
            result = value1 * value2;
            Console.WriteLine($"PositiveInfinity: {Double.IsPositiveInfinity(result)}");
            Console.WriteLine($"NegativeInfinity: {Double.IsNegativeInfinity(result)}");
        }
    }
    
    // The example displays the following output:
    //       PositiveInfinity: True
    //       NegativeInfinity: False
    //
    //       PositiveInfinity: False
    //       NegativeInfinity: True
    
    open System
    
    let value1 = 4.565e153
    let value2 = 6.9375e172
    let result = value1 * value2
    printfn $"PositiveInfinity: {Double.IsPositiveInfinity result}"
    printfn $"NegativeInfinity: {Double.IsNegativeInfinity result}\n"
    
    let value3 = - value1
    let result2 = value2 * value3
    printfn $"PositiveInfinity: {Double.IsPositiveInfinity result2}"
    printfn $"NegativeInfinity: {Double.IsNegativeInfinity result2}"
    
    // The example displays the following output:
    //       PositiveInfinity: True
    //       NegativeInfinity: False
    //
    //       PositiveInfinity: False
    //       NegativeInfinity: True
    
    Module Example8
        Public Sub Main()
            Dim value1 As Double = 4.565E+153
            Dim value2 As Double = 6.9375E+172
            Dim result As Double = value1 * value2
            Console.WriteLine("PositiveInfinity: {0}",
                             Double.IsPositiveInfinity(result))
            Console.WriteLine("NegativeInfinity: {0}",
                            Double.IsNegativeInfinity(result))
            Console.WriteLine()
            value1 = -value1
            result = value1 * value2
            Console.WriteLine("PositiveInfinity: {0}",
                             Double.IsPositiveInfinity(result))
            Console.WriteLine("NegativeInfinity: {0}",
                            Double.IsNegativeInfinity(result))
        End Sub
    End Module
    ' The example displays the following output:
    '       PositiveInfinity: True
    '       NegativeInfinity: False
    '       
    '       PositiveInfinity: False
    '       NegativeInfinity: True
    

    PositiveInfinity 또한 양의 배수를 0으로 나누기에서 비롯된 결과이며, NegativeInfinity은 음의 배수를 0으로 나누기에서 비롯된 결과입니다.

  • 부동 소수점 연산이 유효하지 않으면 그 연산의 결과는 NaN입니다. 예를 들어, 다음 연산의 결과는 NaN입니다.

    • 배당금이 0인 0으로 나누기. 다른 경우에 0으로 나누면 PositiveInfinity 또는 NegativeInfinity이 발생할 수 있음을 유의하십시오.

    • 잘못된 입력이 있는 모든 부동 소수점 작업. 예를 들어 음수 Math.Sqrt 값으로 메서드를 호출하면 1보다 크거나 음수 NaN 보다 작은 값으로 메서드를 호출하는 것과 마찬가지로 반환Math.Acos됩니다.

    • 값이 Double.NaN인수가 있는 모든 연산입니다.

형식 변환

Double 구조체는 명시적 또는 암시적 변환 연산자를 정의하지 않습니다. 대신 변환은 컴파일러에 의해 구현됩니다.

기본 숫자 형식의 값을 a Double 로 변환하는 것은 확대 변환이므로 컴파일러가 명시적으로 요구하지 않는 한 명시적 캐스트 연산자 또는 변환 메서드 호출이 필요하지 않습니다. 예를 들어 C# 컴파일러는 Decimal에서 Double 변환하는 데 캐스팅 연산자가 필요하지만 Visual Basic 컴파일러는 변환하지 않습니다. 다음 예제에서는 다른 기본 숫자 형식의 최소값 또는 최대값을 로 Double변환합니다.

dynamic[] values = { Byte.MinValue, Byte.MaxValue, Decimal.MinValue,
                   Decimal.MaxValue, Int16.MinValue, Int16.MaxValue,
                   Int32.MinValue, Int32.MaxValue, Int64.MinValue,
                   Int64.MaxValue, SByte.MinValue, SByte.MaxValue,
                   Single.MinValue, Single.MaxValue, UInt16.MinValue,
                   UInt16.MaxValue, UInt32.MinValue, UInt32.MaxValue,
                   UInt64.MinValue, UInt64.MaxValue };
double dblValue;
foreach (dynamic value in values)
{
    if (value.GetType() == typeof(decimal))
        dblValue = (double)value;
    else
        dblValue = value;
    Console.WriteLine($"{value} ({value.GetType().Name}) --> " +
        $"{dblValue:R} ({dblValue.GetType().Name})");
}

// The example displays the following output:
//    0 (Byte) --> 0 (Double)
//    255 (Byte) --> 255 (Double)
//    -79228162514264337593543950335 (Decimal) --> -7.9228162514264338E+28 (Double)
//    79228162514264337593543950335 (Decimal) --> 7.9228162514264338E+28 (Double)
//    -32768 (Int16) --> -32768 (Double)
//    32767 (Int16) --> 32767 (Double)
//    -2147483648 (Int32) --> -2147483648 (Double)
//    2147483647 (Int32) --> 2147483647 (Double)
//    -9223372036854775808 (Int64) --> -9.2233720368547758E+18 (Double)
//    9223372036854775807 (Int64) --> 9.2233720368547758E+18 (Double)
//    -128 (SByte) --> -128 (Double)
//    127 (SByte) --> 127 (Double)
//    -3.402823E+38 (Single) --> -3.4028234663852886E+38 (Double)
//    3.402823E+38 (Single) --> 3.4028234663852886E+38 (Double)
//    0 (UInt16) --> 0 (Double)
//    65535 (UInt16) --> 65535 (Double)
//    0 (UInt32) --> 0 (Double)
//    4294967295 (UInt32) --> 4294967295 (Double)
//    0 (UInt64) --> 0 (Double)
//    18446744073709551615 (UInt64) --> 1.8446744073709552E+19 (Double)
open System

let values: obj[] = 
    [| Byte.MinValue; Byte.MaxValue; Decimal.MinValue
       Decimal.MaxValue; Int16.MinValue; Int16.MaxValue
       Int32.MinValue; Int32.MaxValue; Int64.MinValue
       Int64.MaxValue; SByte.MinValue; SByte.MaxValue
       Single.MinValue; Single.MaxValue; UInt16.MinValue
       UInt16.MaxValue; UInt32.MinValue, UInt32.MaxValue
       UInt64.MinValue; UInt64.MaxValue |]

for value in values do
    let dblValue = value :?> double
    printfn $"{value} ({value.GetType().Name}) --> {dblValue:R} ({dblValue.GetType().Name})"
// The example displays the following output:
//    0 (Byte) --> 0 (Double)
//    255 (Byte) --> 255 (Double)
//    -79228162514264337593543950335 (Decimal) --> -7.9228162514264338E+28 (Double)
//    79228162514264337593543950335 (Decimal) --> 7.9228162514264338E+28 (Double)
//    -32768 (Int16) --> -32768 (Double)
//    32767 (Int16) --> 32767 (Double)
//    -2147483648 (Int32) --> -2147483648 (Double)
//    2147483647 (Int32) --> 2147483647 (Double)
//    -9223372036854775808 (Int64) --> -9.2233720368547758E+18 (Double)
//    9223372036854775807 (Int64) --> 9.2233720368547758E+18 (Double)
//    -128 (SByte) --> -128 (Double)
//    127 (SByte) --> 127 (Double)
//    -3.402823E+38 (Single) --> -3.4028234663852886E+38 (Double)
//    3.402823E+38 (Single) --> 3.4028234663852886E+38 (Double)
//    0 (UInt16) --> 0 (Double)
//    65535 (UInt16) --> 65535 (Double)
//    0 (UInt32) --> 0 (Double)
//    4294967295 (UInt32) --> 4294967295 (Double)
//    0 (UInt64) --> 0 (Double)
//    18446744073709551615 (UInt64) --> 1.8446744073709552E+19 (Double)
Module Example5
    Public Sub Main()
        Dim values() As Object = {Byte.MinValue, Byte.MaxValue, Decimal.MinValue,
                                 Decimal.MaxValue, Int16.MinValue, Int16.MaxValue,
                                 Int32.MinValue, Int32.MaxValue, Int64.MinValue,
                                 Int64.MaxValue, SByte.MinValue, SByte.MaxValue,
                                 Single.MinValue, Single.MaxValue, UInt16.MinValue,
                                 UInt16.MaxValue, UInt32.MinValue, UInt32.MaxValue,
                                 UInt64.MinValue, UInt64.MaxValue}
        Dim dblValue As Double
        For Each value In values
            dblValue = value
            Console.WriteLine("{0} ({1}) --> {2:R} ({3})",
                           value, value.GetType().Name,
                           dblValue, dblValue.GetType().Name)
        Next
    End Sub
End Module
' The example displays the following output:
'    0 (Byte) --> 0 (Double)
'    255 (Byte) --> 255 (Double)
'    -79228162514264337593543950335 (Decimal) --> -7.9228162514264338E+28 (Double)
'    79228162514264337593543950335 (Decimal) --> 7.9228162514264338E+28 (Double)
'    -32768 (Int16) --> -32768 (Double)
'    32767 (Int16) --> 32767 (Double)
'    -2147483648 (Int32) --> -2147483648 (Double)
'    2147483647 (Int32) --> 2147483647 (Double)
'    -9223372036854775808 (Int64) --> -9.2233720368547758E+18 (Double)
'    9223372036854775807 (Int64) --> 9.2233720368547758E+18 (Double)
'    -128 (SByte) --> -128 (Double)
'    127 (SByte) --> 127 (Double)
'    -3.402823E+38 (Single) --> -3.4028234663852886E+38 (Double)
'    3.402823E+38 (Single) --> 3.4028234663852886E+38 (Double)
'    0 (UInt16) --> 0 (Double)
'    65535 (UInt16) --> 65535 (Double)
'    0 (UInt32) --> 0 (Double)
'    4294967295 (UInt32) --> 4294967295 (Double)
'    0 (UInt64) --> 0 (Double)
'    18446744073709551615 (UInt64) --> 1.8446744073709552E+19 (Double)

또한 SingleSingle.NaN, Single.PositiveInfinitySingle.NegativeInfinity은 각각 Double.NaN, Double.PositiveInfinityDouble.NegativeInfinity으로 변환됩니다.

일부 숫자 형식의 값을 Double 값으로 변환하면 정밀도가 떨어질 수 있습니다. 예시에서 설명하듯이 Decimal, Int64, 및 UInt64 값을 Double 값으로 변환할 때 정밀도 손실이 발생할 수 있습니다.

Double 값을 다른 기본 숫자 데이터 형식의 값으로 변환하려면 축소 변환이며 캐스트 연산자(C#), 변환 메서드(Visual Basic) 또는 Convert 메서드 호출이 필요합니다. 대상 형식의 MinValueMaxValue 속성으로 정의된 대상 데이터 형식의 범위를 벗어난 값은 다음 표와 같이 동작합니다.

대상 형식 결과
모든 정수 계열 형식 확인된 컨텍스트에서 변환이 발생하는 경우 OverflowException 예외입니다.

확인되지 않은 컨텍스트(C#의 기본값)에서 변환이 발생하면 변환 작업이 성공하지만 값이 오버플로됩니다.
Decimal 예외입니다 OverflowException .
Single Single.NegativeInfinity 음수 값의 경우

Single.PositiveInfinity 양수 값에 대해.

또한 Double.NaN, Double.PositiveInfinityDouble.NegativeInfinity는 확인된 컨텍스트에서 정수로 변환하기 위한 OverflowException을 던지지만, 이러한 값은 확인되지 않은 컨텍스트에서 정수로 변환될 때 오버플로가 발생합니다. Decimal변환을 할 때는 항상 OverflowException를 던집니다. Single변환의 경우 각각 Single.NaN, Single.PositiveInfinitySingle.NegativeInfinity변환합니다.

정밀도 손실은 Double 값을 다른 숫자 형식으로 변환할 때 발생할 수 있습니다. 예제의 출력에서와 같이 정수 계열 형식으로 변환하는 경우 Double 값이 Visual Basic 반올림되거나 잘리면(C#에서와 같이) 소수 구성 요소가 손실됩니다. 두 값 DecimalSingle로 변환할 때, Double 값이 대상 데이터 형식에 정확하게 표현되지 않을 수 있습니다.

다음 예제에서는 여러 Double 값을 다른 여러 숫자 형식으로 변환합니다. 변환은 기본적으로 Visual Basic에서 발생하며, C#에서는 checked 키워드로 인해, F#에서는 Checked 모듈로 인해 발생합니다. 예제의 출력은 확인된 선택되지 않은 컨텍스트 모두에서 변환 결과를 보여 줍니다. Visual Basic에서 /removeintchecks+ 컴파일러 스위치를 사용하여 컴파일하고, C#에서 checked 문을 주석 처리하고, F#에서 open Checked 문을 주석 처리하여 확인되지 않은 컨텍스트에서 변환을 수행할 수 있습니다.

using System;

public class Example5
{
    public static void Main()
    {
        Double[] values = { Double.MinValue, -67890.1234, -12345.6789,
                          12345.6789, 67890.1234, Double.MaxValue,
                          Double.NaN, Double.PositiveInfinity,
                          Double.NegativeInfinity };
        checked
        {
            foreach (var value in values)
            {
                try
                {
                    Int64 lValue = (long)value;
                    Console.WriteLine($"{value} ({value.GetType().Name}) --> {lValue} (0x{lValue:X16}) ({lValue.GetType().Name})");
                }
                catch (OverflowException)
                {
                    Console.WriteLine($"Unable to convert {value} to Int64.");
                }
                try
                {
                    UInt64 ulValue = (ulong)value;
                    Console.WriteLine($"{value} ({value.GetType().Name}) --> {ulValue} (0x{ulValue:X16}) ({ulValue.GetType().Name})");
                }
                catch (OverflowException)
                {
                    Console.WriteLine($"Unable to convert {value} to UInt64.");
                }
                try
                {
                    Decimal dValue = (decimal)value;
                    Console.WriteLine($"{value} ({value.GetType().Name}) --> {dValue} ({dValue.GetType().Name})");
                }
                catch (OverflowException)
                {
                    Console.WriteLine($"Unable to convert {value} to Decimal.");
                }
                try
                {
                    Single sValue = (float)value;
                    Console.WriteLine($"{value} ({value.GetType().Name}) --> {sValue} ({sValue.GetType().Name})");
                }
                catch (OverflowException)
                {
                    Console.WriteLine($"Unable to convert {value} to Single.");
                }
                Console.WriteLine();
            }
        }
    }
}
// The example displays the following output for conversions performed
// in a checked context:
//       Unable to convert -1.79769313486232E+308 to Int64.
//       Unable to convert -1.79769313486232E+308 to UInt64.
//       Unable to convert -1.79769313486232E+308 to Decimal.
//       -1.79769313486232E+308 (Double) --> -Infinity (Single)
//
//       -67890.1234 (Double) --> -67890 (0xFFFFFFFFFFFEF6CE) (Int64)
//       Unable to convert -67890.1234 to UInt64.
//       -67890.1234 (Double) --> -67890.1234 (Decimal)
//       -67890.1234 (Double) --> -67890.13 (Single)
//
//       -12345.6789 (Double) --> -12345 (0xFFFFFFFFFFFFCFC7) (Int64)
//       Unable to convert -12345.6789 to UInt64.
//       -12345.6789 (Double) --> -12345.6789 (Decimal)
//       -12345.6789 (Double) --> -12345.68 (Single)
//
//       12345.6789 (Double) --> 12345 (0x0000000000003039) (Int64)
//       12345.6789 (Double) --> 12345 (0x0000000000003039) (UInt64)
//       12345.6789 (Double) --> 12345.6789 (Decimal)
//       12345.6789 (Double) --> 12345.68 (Single)
//
//       67890.1234 (Double) --> 67890 (0x0000000000010932) (Int64)
//       67890.1234 (Double) --> 67890 (0x0000000000010932) (UInt64)
//       67890.1234 (Double) --> 67890.1234 (Decimal)
//       67890.1234 (Double) --> 67890.13 (Single)
//
//       Unable to convert 1.79769313486232E+308 to Int64.
//       Unable to convert 1.79769313486232E+308 to UInt64.
//       Unable to convert 1.79769313486232E+308 to Decimal.
//       1.79769313486232E+308 (Double) --> Infinity (Single)
//
//       Unable to convert NaN to Int64.
//       Unable to convert NaN to UInt64.
//       Unable to convert NaN to Decimal.
//       NaN (Double) --> NaN (Single)
//
//       Unable to convert Infinity to Int64.
//       Unable to convert Infinity to UInt64.
//       Unable to convert Infinity to Decimal.
//       Infinity (Double) --> Infinity (Single)
//
//       Unable to convert -Infinity to Int64.
//       Unable to convert -Infinity to UInt64.
//       Unable to convert -Infinity to Decimal.
//       -Infinity (Double) --> -Infinity (Single)
// The example displays the following output for conversions performed
// in an unchecked context:
//       -1.79769313486232E+308 (Double) --> -9223372036854775808 (0x8000000000000000) (Int64)
//       -1.79769313486232E+308 (Double) --> 9223372036854775808 (0x8000000000000000) (UInt64)
//       Unable to convert -1.79769313486232E+308 to Decimal.
//       -1.79769313486232E+308 (Double) --> -Infinity (Single)
//
//       -67890.1234 (Double) --> -67890 (0xFFFFFFFFFFFEF6CE) (Int64)
//       -67890.1234 (Double) --> 18446744073709483726 (0xFFFFFFFFFFFEF6CE) (UInt64)
//       -67890.1234 (Double) --> -67890.1234 (Decimal)
//       -67890.1234 (Double) --> -67890.13 (Single)
//
//       -12345.6789 (Double) --> -12345 (0xFFFFFFFFFFFFCFC7) (Int64)
//       -12345.6789 (Double) --> 18446744073709539271 (0xFFFFFFFFFFFFCFC7) (UInt64)
//       -12345.6789 (Double) --> -12345.6789 (Decimal)
//       -12345.6789 (Double) --> -12345.68 (Single)
//
//       12345.6789 (Double) --> 12345 (0x0000000000003039) (Int64)
//       12345.6789 (Double) --> 12345 (0x0000000000003039) (UInt64)
//       12345.6789 (Double) --> 12345.6789 (Decimal)
//       12345.6789 (Double) --> 12345.68 (Single)
//
//       67890.1234 (Double) --> 67890 (0x0000000000010932) (Int64)
//       67890.1234 (Double) --> 67890 (0x0000000000010932) (UInt64)
//       67890.1234 (Double) --> 67890.1234 (Decimal)
//       67890.1234 (Double) --> 67890.13 (Single)
//
//       1.79769313486232E+308 (Double) --> -9223372036854775808 (0x8000000000000000) (Int64)
//       1.79769313486232E+308 (Double) --> 0 (0x0000000000000000) (UInt64)
//       Unable to convert 1.79769313486232E+308 to Decimal.
//       1.79769313486232E+308 (Double) --> Infinity (Single)
//
//       NaN (Double) --> -9223372036854775808 (0x8000000000000000) (Int64)
//       NaN (Double) --> 0 (0x0000000000000000) (UInt64)
//       Unable to convert NaN to Decimal.
//       NaN (Double) --> NaN (Single)
//
//       Infinity (Double) --> -9223372036854775808 (0x8000000000000000) (Int64)
//       Infinity (Double) --> 0 (0x0000000000000000) (UInt64)
//       Unable to convert Infinity to Decimal.
//       Infinity (Double) --> Infinity (Single)
//
//       -Infinity (Double) --> -9223372036854775808 (0x8000000000000000) (Int64)
//       -Infinity (Double) --> 9223372036854775808 (0x8000000000000000) (UInt64)
//       Unable to convert -Infinity to Decimal.
//       -Infinity (Double) --> -Infinity (Single)
open System
open Checked

let values = 
    [| Double.MinValue; -67890.1234; -12345.6789
       12345.6789; 67890.1234; Double.MaxValue
       Double.NaN; Double.PositiveInfinity;
       Double.NegativeInfinity |]

for value in values do
    try
        let lValue = int64 value
        printfn $"{value} ({value.GetType().Name}) --> {lValue} (0x{lValue:X16}) ({lValue.GetType().Name})"
    with :? OverflowException ->
        printfn $"Unable to convert {value} to Int64."
    try
        let ulValue = uint64 value
        printfn $"{value} ({value.GetType().Name}) --> {ulValue} (0x{ulValue:X16}) ({ulValue.GetType().Name})"
    with :? OverflowException ->
        printfn $"Unable to convert {value} to UInt64."
    try
        let dValue = decimal value
        printfn $"{value} ({value.GetType().Name}) --> {dValue} ({dValue.GetType().Name})"
    with :? OverflowException ->
        printfn $"Unable to convert {value} to Decimal."
    try
        let sValue = float32 value
        printfn $"{value} ({value.GetType().Name}) --> {sValue} ({sValue.GetType().Name})"
    with :? OverflowException ->
        printfn $"Unable to convert {value} to Single."
    printfn ""
// The example displays the following output for conversions performed
// in a checked context:
//       Unable to convert -1.79769313486232E+308 to Int64.
//       Unable to convert -1.79769313486232E+308 to UInt64.
//       Unable to convert -1.79769313486232E+308 to Decimal.
//       -1.79769313486232E+308 (Double) --> -Infinity (Single)
//
//       -67890.1234 (Double) --> -67890 (0xFFFFFFFFFFFEF6CE) (Int64)
//       Unable to convert -67890.1234 to UInt64.
//       -67890.1234 (Double) --> -67890.1234 (Decimal)
//       -67890.1234 (Double) --> -67890.13 (Single)
//
//       -12345.6789 (Double) --> -12345 (0xFFFFFFFFFFFFCFC7) (Int64)
//       Unable to convert -12345.6789 to UInt64.
//       -12345.6789 (Double) --> -12345.6789 (Decimal)
//       -12345.6789 (Double) --> -12345.68 (Single)
//
//       12345.6789 (Double) --> 12345 (0x0000000000003039) (Int64)
//       12345.6789 (Double) --> 12345 (0x0000000000003039) (UInt64)
//       12345.6789 (Double) --> 12345.6789 (Decimal)
//       12345.6789 (Double) --> 12345.68 (Single)
//
//       67890.1234 (Double) --> 67890 (0x0000000000010932) (Int64)
//       67890.1234 (Double) --> 67890 (0x0000000000010932) (UInt64)
//       67890.1234 (Double) --> 67890.1234 (Decimal)
//       67890.1234 (Double) --> 67890.13 (Single)
//
//       Unable to convert 1.79769313486232E+308 to Int64.
//       Unable to convert 1.79769313486232E+308 to UInt64.
//       Unable to convert 1.79769313486232E+308 to Decimal.
//       1.79769313486232E+308 (Double) --> Infinity (Single)
//
//       Unable to convert NaN to Int64.
//       Unable to convert NaN to UInt64.
//       Unable to convert NaN to Decimal.
//       NaN (Double) --> NaN (Single)
//
//       Unable to convert Infinity to Int64.
//       Unable to convert Infinity to UInt64.
//       Unable to convert Infinity to Decimal.
//       Infinity (Double) --> Infinity (Single)
//
//       Unable to convert -Infinity to Int64.
//       Unable to convert -Infinity to UInt64.
//       Unable to convert -Infinity to Decimal.
//       -Infinity (Double) --> -Infinity (Single)
// The example displays the following output for conversions performed
// in an unchecked context:
//       -1.79769313486232E+308 (Double) --> -9223372036854775808 (0x8000000000000000) (Int64)
//       -1.79769313486232E+308 (Double) --> 9223372036854775808 (0x8000000000000000) (UInt64)
//       Unable to convert -1.79769313486232E+308 to Decimal.
//       -1.79769313486232E+308 (Double) --> -Infinity (Single)
//
//       -67890.1234 (Double) --> -67890 (0xFFFFFFFFFFFEF6CE) (Int64)
//       -67890.1234 (Double) --> 18446744073709483726 (0xFFFFFFFFFFFEF6CE) (UInt64)
//       -67890.1234 (Double) --> -67890.1234 (Decimal)
//       -67890.1234 (Double) --> -67890.13 (Single)
//
//       -12345.6789 (Double) --> -12345 (0xFFFFFFFFFFFFCFC7) (Int64)
//       -12345.6789 (Double) --> 18446744073709539271 (0xFFFFFFFFFFFFCFC7) (UInt64)
//       -12345.6789 (Double) --> -12345.6789 (Decimal)
//       -12345.6789 (Double) --> -12345.68 (Single)
//
//       12345.6789 (Double) --> 12345 (0x0000000000003039) (Int64)
//       12345.6789 (Double) --> 12345 (0x0000000000003039) (UInt64)
//       12345.6789 (Double) --> 12345.6789 (Decimal)
//       12345.6789 (Double) --> 12345.68 (Single)
//
//       67890.1234 (Double) --> 67890 (0x0000000000010932) (Int64)
//       67890.1234 (Double) --> 67890 (0x0000000000010932) (UInt64)
//       67890.1234 (Double) --> 67890.1234 (Decimal)
//       67890.1234 (Double) --> 67890.13 (Single)
//
//       1.79769313486232E+308 (Double) --> -9223372036854775808 (0x8000000000000000) (Int64)
//       1.79769313486232E+308 (Double) --> 0 (0x0000000000000000) (UInt64)
//       Unable to convert 1.79769313486232E+308 to Decimal.
//       1.79769313486232E+308 (Double) --> Infinity (Single)
//
//       NaN (Double) --> -9223372036854775808 (0x8000000000000000) (Int64)
//       NaN (Double) --> 0 (0x0000000000000000) (UInt64)
//       Unable to convert NaN to Decimal.
//       NaN (Double) --> NaN (Single)
//
//       Infinity (Double) --> -9223372036854775808 (0x8000000000000000) (Int64)
//       Infinity (Double) --> 0 (0x0000000000000000) (UInt64)
//       Unable to convert Infinity to Decimal.
//       Infinity (Double) --> Infinity (Single)
//
//       -Infinity (Double) --> -9223372036854775808 (0x8000000000000000) (Int64)
//       -Infinity (Double) --> 9223372036854775808 (0x8000000000000000) (UInt64)
//       Unable to convert -Infinity to Decimal.
//       -Infinity (Double) --> -Infinity (Single)
Module Example6
    Public Sub Main()
        Dim values() As Double = {Double.MinValue, -67890.1234, -12345.6789,
                                 12345.6789, 67890.1234, Double.MaxValue,
                                 Double.NaN, Double.PositiveInfinity,
                                 Double.NegativeInfinity}
        For Each value In values
            Try
                Dim lValue As Int64 = CLng(value)
                Console.WriteLine("{0} ({1}) --> {2} (0x{2:X16}) ({3})",
                               value, value.GetType().Name,
                               lValue, lValue.GetType().Name)
            Catch e As OverflowException
                Console.WriteLine("Unable to convert {0} to Int64.", value)
            End Try
            Try
                Dim ulValue As UInt64 = CULng(value)
                Console.WriteLine("{0} ({1}) --> {2} (0x{2:X16}) ({3})",
                               value, value.GetType().Name,
                               ulValue, ulValue.GetType().Name)
            Catch e As OverflowException
                Console.WriteLine("Unable to convert {0} to UInt64.", value)
            End Try
            Try
                Dim dValue As Decimal = CDec(value)
                Console.WriteLine("{0} ({1}) --> {2} ({3})",
                               value, value.GetType().Name,
                               dValue, dValue.GetType().Name)
            Catch e As OverflowException
                Console.WriteLine("Unable to convert {0} to Decimal.", value)
            End Try
            Try
                Dim sValue As Single = CSng(value)
                Console.WriteLine("{0} ({1}) --> {2} ({3})",
                               value, value.GetType().Name,
                               sValue, sValue.GetType().Name)
            Catch e As OverflowException
                Console.WriteLine("Unable to convert {0} to Single.", value)
            End Try
            Console.WriteLine()
        Next
    End Sub
End Module
' The example displays the following output for conversions performed
' in a checked context:
'       Unable to convert -1.79769313486232E+308 to Int64.
'       Unable to convert -1.79769313486232E+308 to UInt64.
'       Unable to convert -1.79769313486232E+308 to Decimal.
'       -1.79769313486232E+308 (Double) --> -Infinity (Single)
'
'       -67890.1234 (Double) --> -67890 (0xFFFFFFFFFFFEF6CE) (Int64)
'       Unable to convert -67890.1234 to UInt64.
'       -67890.1234 (Double) --> -67890.1234 (Decimal)
'       -67890.1234 (Double) --> -67890.13 (Single)
'
'       -12345.6789 (Double) --> -12346 (0xFFFFFFFFFFFFCFC6) (Int64)
'       Unable to convert -12345.6789 to UInt64.
'       -12345.6789 (Double) --> -12345.6789 (Decimal)
'       -12345.6789 (Double) --> -12345.68 (Single)
'
'       12345.6789 (Double) --> 12346 (0x000000000000303A) (Int64)
'       12345.6789 (Double) --> 12346 (0x000000000000303A) (UInt64)
'       12345.6789 (Double) --> 12345.6789 (Decimal)
'       12345.6789 (Double) --> 12345.68 (Single)
'
'       67890.1234 (Double) --> 67890 (0x0000000000010932) (Int64)
'       67890.1234 (Double) --> 67890 (0x0000000000010932) (UInt64)
'       67890.1234 (Double) --> 67890.1234 (Decimal)
'       67890.1234 (Double) --> 67890.13 (Single)
'
'       Unable to convert 1.79769313486232E+308 to Int64.
'       Unable to convert 1.79769313486232E+308 to UInt64.
'       Unable to convert 1.79769313486232E+308 to Decimal.
'       1.79769313486232E+308 (Double) --> Infinity (Single)
'
'       Unable to convert NaN to Int64.
'       Unable to convert NaN to UInt64.
'       Unable to convert NaN to Decimal.
'       NaN (Double) --> NaN (Single)
'
'       Unable to convert Infinity to Int64.
'       Unable to convert Infinity to UInt64.
'       Unable to convert Infinity to Decimal.
'       Infinity (Double) --> Infinity (Single)
'
'       Unable to convert -Infinity to Int64.
'       Unable to convert -Infinity to UInt64.
'       Unable to convert -Infinity to Decimal.
'       -Infinity (Double) --> -Infinity (Single)
' The example displays the following output for conversions performed
' in an unchecked context:
'       -1.79769313486232E+308 (Double) --> -9223372036854775808 (0x8000000000000000) (Int64)
'       -1.79769313486232E+308 (Double) --> 9223372036854775808 (0x8000000000000000) (UInt64)
'       Unable to convert -1.79769313486232E+308 to Decimal.
'       -1.79769313486232E+308 (Double) --> -Infinity (Single)
'
'       -67890.1234 (Double) --> -67890 (0xFFFFFFFFFFFEF6CE) (Int64)
'       -67890.1234 (Double) --> 18446744073709483726 (0xFFFFFFFFFFFEF6CE) (UInt64)
'       -67890.1234 (Double) --> -67890.1234 (Decimal)
'       -67890.1234 (Double) --> -67890.13 (Single)
'
'       -12345.6789 (Double) --> -12346 (0xFFFFFFFFFFFFCFC6) (Int64)
'       -12345.6789 (Double) --> 18446744073709539270 (0xFFFFFFFFFFFFCFC6) (UInt64)
'       -12345.6789 (Double) --> -12345.6789 (Decimal)
'       -12345.6789 (Double) --> -12345.68 (Single)
'
'       12345.6789 (Double) --> 12346 (0x000000000000303A) (Int64)
'       12345.6789 (Double) --> 12346 (0x000000000000303A) (UInt64)
'       12345.6789 (Double) --> 12345.6789 (Decimal)
'       12345.6789 (Double) --> 12345.68 (Single)
'
'       67890.1234 (Double) --> 67890 (0x0000000000010932) (Int64)
'       67890.1234 (Double) --> 67890 (0x0000000000010932) (UInt64)
'       67890.1234 (Double) --> 67890.1234 (Decimal)
'       67890.1234 (Double) --> 67890.13 (Single)
'
'       1.79769313486232E+308 (Double) --> -9223372036854775808 (0x8000000000000000) (Int64)
'       1.79769313486232E+308 (Double) --> 0 (0x0000000000000000) (UInt64)
'       Unable to convert 1.79769313486232E+308 to Decimal.
'       1.79769313486232E+308 (Double) --> Infinity (Single)
'
'       NaN (Double) --> -9223372036854775808 (0x8000000000000000) (Int64)
'       NaN (Double) --> 0 (0x0000000000000000) (UInt64)
'       Unable to convert NaN to Decimal.
'       NaN (Double) --> NaN (Single)
'
'       Infinity (Double) --> -9223372036854775808 (0x8000000000000000) (Int64)
'       Infinity (Double) --> 0 (0x0000000000000000) (UInt64)
'       Unable to convert Infinity to Decimal.
'       Infinity (Double) --> Infinity (Single)
'
'       -Infinity (Double) --> -9223372036854775808 (0x8000000000000000) (Int64)
'       -Infinity (Double) --> 9223372036854775808 (0x8000000000000000) (UInt64)
'       Unable to convert -Infinity to Decimal.
'       -Infinity (Double) --> -Infinity (Single)

숫자 형식의 변환에 대한 자세한 내용은 .NETType 변환 테이블의 형식 변환을 참조하세요.

부동 소수점 기능

구조체 및 관련 형식은 Double 다음 영역에서 작업을 수행하는 메서드를 제공합니다.

  • 값의 비교입니다. Equals 메서드를 호출하여 두 Double 값이 같은지 또는 CompareTo 메서드를 호출하여 두 값 간의 관계를 확인할 수 있습니다.

    Double 구조체는 전체 비교 연산자 집합도 지원합니다. 예를 들어 같음 또는 같지 않음을 테스트하거나 한 값이 다른 값보다 크거나 같은지 확인할 수 있습니다. 피연산자 중 하나가 숫자 형식이 아닌 Double인 경우, 비교를 수행하기 전에 Double로 변환됩니다.

    경고

    정밀도의 차이로 인해 같을 것으로 예상되는 두 Double 값이 같지 않은 것으로 판명되어 비교 결과에 영향을 줄 수 있습니다. 두 Double 값을 비교하는 방법에 대한 자세한 내용은 ‘동일성 테스트’ 섹션을 참조하세요.

    IsNaN, IsInfinity, IsPositiveInfinityIsNegativeInfinity 메서드를 호출하여 이러한 특수 값을 테스트할 수도 있습니다.

  • 수학 연산. 더하기, 빼기, 곱하기 및 나누기와 같은 일반적인 산술 연산은 메서드가 아닌 언어 컴파일러 및 CIL(공용 중간 언어) 명령에 의해 Double 구현됩니다. 수학 연산의 피연산자 중 하나가 Double가 아닌 다른 숫자 형식인 경우, 연산을 수행하기 전에 Double로 변환됩니다. 작업의 결과도 Double 값입니다.

    다른 수학 연산은 static 클래스에서 Shared(Visual Basic System.Math) 메서드를 호출하여 수행할 수 있습니다. 여기에는 산술(예: Math.Abs, Math.SignMath.Sqrt), 기하(예: Math.CosMath.Sin), 그리고 미적분(예: Math.Log)에 일반적으로 사용되는 추가적인 메서드가 포함됩니다.

    Double 값의 개별 비트를 조작할 수도 있습니다. 이 메서드는 BitConverter.DoubleToInt64Bits 값의 비트 패턴을 64비트 정수로 유지합니다 Double . BitConverter.GetBytes(Double) 메서드는 바이트 배열에서 비트 패턴을 반환합니다.

  • 반올림. 반올림은 부동 소수점 표현과 정밀도 문제로 인해 발생하는 값 간의 차이를 줄이는 기술로 자주 사용됩니다. Double 메서드를 호출하여 Math.Round 값을 반올림할 수 있습니다.

  • 서식. 값을 문자열로 변환하려면 Double 메서드를 호출하거나 복합 서식 지정 기능을 사용하세요. 서식 문자열이 부동 소수점 값의 문자열 표현을 제어하는 방법에 대한 자세한 내용은 표준 숫자 형식 문자열사용자 지정 숫자 형식 문자열을 참조하세요.

  • 문자열구문 분석. 당신은 Double 또는 Parse 메서드를 호출하여 부동 소수점 값의 문자열 표현을 TryParse 값으로 변환할 수 있습니다. 구문 분석 작업이 실패하면 Parse 메서드는 예외를 throw하는 반면 TryParse 메서드는 false반환합니다.

  • 형식 변환. Double 구조체는 두 표준 .NET 데이터 형식 간의 변환을 지원하는 IConvertible 인터페이스에 대한 명시적 인터페이스 구현을 제공합니다. 언어 컴파일러에서는 다른 모든 표준 숫자 형식의 값을 Double 값으로 암시적으로 변환하는 것도 지원합니다. 표준 숫자 형식의 값을 a Double 로 변환하는 것은 확대 변환이며 캐스팅 연산자 또는 변환 메서드의 사용자가 필요하지 않습니다.

    그러나 Int64Single 값의 변환에는 정밀도 손실이 발생할 수 있습니다. 다음 표에서는 이러한 각 형식의 정밀도 차이를 보여줍니다.

    유형 최대 정밀도 내부 정밀도
    Double 15 17
    Int64 19자리 십진수 19자리 십진수
    Single 10진수 7자리 10진수 9자리

    정밀도 문제는 Single 값으로 변환되는 Double 값에 가장 자주 영향을 줍니다. 다음 예제에서는 값 중 하나가 단정밀도 부동 소수점 값 Double이므로 동일한 나누기 연산에서 생성된 두 값은 같지 않습니다.

    using System;
    
    public class Example13
    {
        public static void Main()
        {
            Double value = .1;
            Double result1 = value * 10;
            Double result2 = 0;
            for (int ctr = 1; ctr <= 10; ctr++)
                result2 += value;
    
            Console.WriteLine($".1 * 10:           {result1:R}");
            Console.WriteLine($".1 Added 10 times: {result2:R}");
        }
    }
    // The example displays the following output:
    //       .1 * 10:           1
    //       .1 Added 10 times: 0.99999999999999989
    
    let value = 0.1
    let result1 = value * 10.
    let mutable result2 = 0.
    for i = 1 to 10 do
        result2 <- result2 + value
    
    printfn $".1 * 10:           {result1:R}"
    printfn $".1 Added 10 times: {result2:R}"
    // The example displays the following output:
    //       .1 * 10:           1
    //       .1 Added 10 times: 0.99999999999999989
    
    Module Example14
        Public Sub Main()
            Dim value As Double = 0.1
            Dim result1 As Double = value * 10
            Dim result2 As Double
            For ctr As Integer = 1 To 10
                result2 += value
            Next
            Console.WriteLine(".1 * 10:           {0:R}", result1)
            Console.WriteLine(".1 Added 10 times: {0:R}", result2)
        End Sub
    End Module
    ' The example displays the following output:
    '       .1 * 10:           1
    '       .1 Added 10 times: 0.99999999999999989
    

예시

다음 코드 예제에서는 다음을 Double사용하는 방법을 보여 줍니다.

// The Temperature class stores the temperature as a Double
// and delegates most of the functionality to the Double
// implementation.
public class Temperature : IComparable, IFormattable
{
    // IComparable.CompareTo implementation.
    public int CompareTo(object obj) {
        if (obj == null) return 1;

        Temperature temp = obj as Temperature;
        if (obj != null)
            return m_value.CompareTo(temp.m_value);
        else
            throw new ArgumentException("object is not a Temperature");	
    }

    // IFormattable.ToString implementation.
    public string ToString(string format, IFormatProvider provider) {
        if( format != null ) {
            if( format.Equals("F") ) {
                return String.Format("{0}'F", this.Value.ToString());
            }
            if( format.Equals("C") ) {
                return String.Format("{0}'C", this.Celsius.ToString());
            }
        }

        return m_value.ToString(format, provider);
    }

    // Parses the temperature from a string in the form
    // [ws][sign]digits['F|'C][ws]
    public static Temperature Parse(string s, NumberStyles styles, IFormatProvider provider) {
        Temperature temp = new Temperature();

        if( s.TrimEnd(null).EndsWith("'F") ) {
            temp.Value = Double.Parse( s.Remove(s.LastIndexOf('\''), 2), styles, provider);
        }
        else if( s.TrimEnd(null).EndsWith("'C") ) {
            temp.Celsius = Double.Parse( s.Remove(s.LastIndexOf('\''), 2), styles, provider);
        }
        else {
            temp.Value = Double.Parse(s, styles, provider);
        }

        return temp;
    }

    // The value holder
    protected double m_value;

    public double Value {
        get {
            return m_value;
        }
        set {
            m_value = value;
        }
    }

    public double Celsius {
        get {
            return (m_value-32.0)/1.8;
        }
        set {
            m_value = 1.8*value+32.0;
        }
    }
}
// The Temperature class stores the temperature as a Double
// and delegates most of the functionality to the Double
// implementation.
type Temperature() =
    member val Value = 0. with get, set

    member this.Celsius
        with get () = (this.Value - 32.) / 1.8
        and set (value) =
            this.Value <- 1.8 * value + 32.

    // Parses the temperature from a string in the form
    // [ws][sign]digits['F|'C][ws]
    static member Parse(s: string, styles: NumberStyles, provider: IFormatProvider) =
        let temp = Temperature()

        if s.TrimEnd(null).EndsWith "'F" then
            temp.Value <- Double.Parse(s.Remove(s.LastIndexOf '\'', 2), styles, provider)
        elif s.TrimEnd(null).EndsWith "'C" then
            temp.Celsius <- Double.Parse(s.Remove(s.LastIndexOf '\'', 2), styles, provider)
        else
            temp.Value <- Double.Parse(s, styles, provider)
        temp

    interface IComparable with
        // IComparable.CompareTo implementation.
        member this.CompareTo(obj: obj) =
            match obj with 
            | null -> 1
            | :? Temperature as temp ->
                this.Value.CompareTo temp.Value
            | _ ->
                invalidArg "obj" "object is not a Temperature"

    interface IFormattable with
        // IFormattable.ToString implementation.
        member this.ToString(format: string, provider: IFormatProvider) =
            match format with
            | "F" ->
                $"{this.Value}'F"
            | "C" ->
                $"{this.Celsius}'C"
            | _ ->
                this.Value.ToString(format, provider)
' Temperature class stores the value as Double
' and delegates most of the functionality 
' to the Double implementation.
Public Class Temperature
    Implements IComparable, IFormattable

    Public Overloads Function CompareTo(ByVal obj As Object) As Integer _
        Implements IComparable.CompareTo

        If TypeOf obj Is Temperature Then
            Dim temp As Temperature = CType(obj, Temperature)

            Return m_value.CompareTo(temp.m_value)
        End If

        Throw New ArgumentException("object is not a Temperature")
    End Function

    Public Overloads Function ToString(ByVal format As String, ByVal provider As IFormatProvider) As String _
        Implements IFormattable.ToString

        If Not (format Is Nothing) Then
            If format.Equals("F") Then
                Return [String].Format("{0}'F", Me.Value.ToString())
            End If
            If format.Equals("C") Then
                Return [String].Format("{0}'C", Me.Celsius.ToString())
            End If
        End If

        Return m_value.ToString(format, provider)
    End Function

    ' Parses the temperature from a string in form
    ' [ws][sign]digits['F|'C][ws]
    Public Shared Function Parse(ByVal s As String, ByVal styles As NumberStyles, ByVal provider As IFormatProvider) As Temperature
        Dim temp As New Temperature()

        If s.TrimEnd().EndsWith("'F") Then
            temp.Value = Double.Parse(s.Remove(s.LastIndexOf("'"c), 2), styles, provider)
        Else
            If s.TrimEnd().EndsWith("'C") Then
                temp.Celsius = Double.Parse(s.Remove(s.LastIndexOf("'"c), 2), styles, provider)
            Else
                temp.Value = Double.Parse(s, styles, provider)
            End If
        End If
        Return temp
    End Function

    ' The value holder
    Protected m_value As Double

    Public Property Value() As Double
        Get
            Return m_value
        End Get
        Set(ByVal Value As Double)
            m_value = Value
        End Set
    End Property

    Public Property Celsius() As Double
        Get
            Return (m_value - 32) / 1.8
        End Get
        Set(ByVal Value As Double)
            m_value = Value * 1.8 + 32
        End Set
    End Property
End Class