Double 結構

定義

表示雙精度浮點數。Represents a double-precision floating-point number.

public value class Double : IComparable, IComparable<double>, IConvertible, IEquatable<double>, IFormattable
[System.Runtime.InteropServices.ComVisible(true)]
[System.Serializable]
public struct Double : IComparable, IComparable<double>, IConvertible, IEquatable<double>, IFormattable
type double = struct
    interface IFormattable
    interface IConvertible
Public Structure Double
Implements IComparable, IComparable(Of Double), IConvertible, IEquatable(Of Double), IFormattable
繼承
Double
屬性
實作

範例

下列程式碼範例說明如何使用 DoubleThe following code example illustrates the use of Double:

// The Temperature class stores the temperature as a Double
// and delegates most of the functionality to the Double 
// implementation.
public ref class Temperature: public IComparable, public IFormattable
{
   // IComparable.CompareTo implementation.
public:
   virtual int CompareTo( Object^ obj )
   {
      if (obj == nullptr) return 1;
      
      if (dynamic_cast<Temperature^>(obj) )
      {
         Temperature^ temp = (Temperature^)(obj);
         return m_value.CompareTo( temp->m_value );
      }
      throw gcnew ArgumentException( "object is not a Temperature" );
   }

   // IFormattable.ToString implementation.
   virtual String^ ToString( String^ format, IFormatProvider^ provider )
   {
      if ( format != nullptr )
      {
         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]
   static Temperature^ Parse( String^ s, NumberStyles styles, IFormatProvider^ provider )
   {
      Temperature^ temp = gcnew Temperature;

      if ( s->TrimEnd(nullptr)->EndsWith( "'F" ) )
      {
         temp->Value = Double::Parse( s->Remove( s->LastIndexOf( '\'' ), 2 ), styles, provider );
      }
      else
      if ( s->TrimEnd(nullptr)->EndsWith( "'C" ) )
      {
         temp->Celsius = Double::Parse( s->Remove( s->LastIndexOf( '\'' ), 2 ), styles, provider );
      }
      else
      {
         temp->Value = Double::Parse( s, styles, provider );
      }
      return temp;
   }

protected:
   double m_value;

public:
   property double Value 
   {
      double get()
      {
         return m_value;
      }

      void set( double value )
      {
         m_value = value;
      }
   }

   property double Celsius 
   {
      double get()
      {
         return (m_value - 32.0) / 1.8;
      }

      void set( double value )
      {
         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.
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;
        }
    }
}
' 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(Nothing).EndsWith("'F") Then
            temp.Value = Double.Parse(s.Remove(s.LastIndexOf("'"c), 2), styles, provider)
        Else
            If s.TrimEnd(Nothing).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

備註

Double 數值型別代表雙精確度64位數值,其值的範圍從負數 1.79769313486232 e 308 到正的 1.79769313486232 e 308,以及正數或負零、PositiveInfinityNegativeInfinity,而不是數位(NaN)。The Double value type represents a double-precision 64-bit number with values ranging from negative 1.79769313486232e308 to positive 1.79769313486232e308, as well as positive or negative zero, PositiveInfinity, NegativeInfinity, and not a number (NaN). 它的目的是要代表非常大的值(例如,行星或 galaxies 之間的距離),或非常小的(物質的分子大量,以千克計算),而且通常不精確(例如從地球到另一個日光系統的距離),Double 類型符合適用于二進位浮點算術的 IEC 60559:1989 (IEEE 754)標準。It is intended to represent values that are extremely large (such as distances between planets or galaxies) or extremely small (the molecular mass of a substance in kilograms) and that often are imprecise (such as the distance from earth to another solar system), The Double type complies with the IEC 60559:1989 (IEEE 754) standard for binary floating-point arithmetic.

本主題包含下列章節:This topic consists of the following sections:

浮點表示和有效位數Floating-Point Representation and Precision

Double 資料類型會以64位的二進位格式儲存雙精確度浮點值,如下表所示:The Double data type stores double-precision floating-point values in a 64-bit binary format, as shown in the following table:

組件Part BitsBits
有效位數或尾數Significand or mantissa 0-510-51
ExponentExponent 52-6252-62
Sign (0 = 正數,1 = 負數)Sign (0 = Positive, 1 = Negative) 6363

就像小數分數無法精確地表示一些小數值(例如1/3 或 Math.PI),二進位片段無法代表一些小數值。Just as decimal fractions are unable to precisely represent some fractional values (such as 1/3 or Math.PI), binary fractions are unable to represent some fractional values. 例如,1/10 (以0.1 的十進位數表示)會以二進位分數來表示,而001100110011則會以 binary 部分的形式呈現,且模式 "0011" 會重複為無限大。For example, 1/10, which is represented precisely by .1 as a decimal fraction, is represented by .001100110011 as a binary fraction, with the pattern "0011" repeating to infinity. 在此情況下,浮點值會提供它所代表數位的不精確標記法。In this case, the floating-point value provides an imprecise representation of the number that it represents. 在原始浮點值上執行其他數學運算通常會增加缺少的精確度。Performing additional mathematical operations on the original floating-point value often tends to increase its lack of precision. 例如,如果比較 .1 乘以10的結果,並將 .1 增加到 1 9 次,我們就會看到加法,因為它牽涉到八個以上的作業,所以產生的結果比較不精確。For example, if we compare the result of multiplying .1 by 10 and adding .1 to .1 nine times, we see that addition, because it has involved eight more operations, has produced the less precise result. 請注意,只有當我們使用 "R"標準數值格式字串來顯示兩個 Double 值時,才會有明顯的差異,如有必要,則會顯示 Double 類型所支援的所有17位數的精確度。Note that this disparity is apparent only if we display the two Double values by using the "R" standard numeric format string, which if necessary displays all 17 digits of precision supported by the Double type.

using System;

public class Example
{
   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:           {0:R}", result1);
      Console.WriteLine(".1 Added 10 times: {0:R}", result2);
   }
}
// The example displays the following output:
//       .1 * 10:           1
//       .1 Added 10 times: 0.99999999999999989
Module Example
   Public Sub Main()
      Dim value As Double = .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

因為有些數位無法完全表示為小數二進位值,所以浮點數只能近似于實際數位。Because some numbers cannot be represented exactly as fractional binary values, floating-point numbers can only approximate real numbers.

所有浮點數也有有限數目的有效數字,這也會決定浮點值接近實數的精確度。All floating-point numbers also have a limited number of significant digits, which also determines how accurately a floating-point value approximates a real number. Double 值最多可有15個小數位數,但在內部維護最多17位數。A Double value has up to 15 decimal digits of precision, although a maximum of 17 digits is maintained internally. 這表示某些浮點運算可能缺少精確度來變更浮點值。This means that some floating-point operations may lack the precision to change a floating point value. 下列範例提供一個實例。The following example provides an illustration. 它會定義非常大的浮點值,然後將 Double.Epsilon 和一個 quadrillion 的乘積加入其中。It defines a very large floating-point value, and then adds the product of Double.Epsilon and one quadrillion to it. 不過,產品太小,無法修改原始的浮點值。The product, however, is too small to modify the original floating-point value. 它的最小有效位數是萬分之一,而產品中最重要的數位是 10-309Its least significant digit is thousandths, whereas the most significant digit in the product is 10-309.

using System;

public class Example
{
   public static void Main()
   {
      Double value = 123456789012.34567;
      Double additional = Double.Epsilon * 1e15;
      Console.WriteLine("{0} + {1} = {2}", value, additional, 
                                           value + additional);
   }
}
// The example displays the following output:
//    123456789012.346 + 4.94065645841247E-309 = 123456789012.346
Module Example
   Public Sub Main()
      Dim value As Double = 123456789012.34567
      Dim additional As Double = Double.Epsilon * 1e15
      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

浮點數的限制有效位數有數個結果:The limited precision of a floating-point number has several consequences:

  • 針對特定有效位數顯示為相等的兩個浮點數,可能不會比較相等,因為它們的最小值不相同。Two floating-point numbers that appear equal for a particular precision might not compare equal because their least significant digits are different. 在下列範例中,會將一連串的數位相加,並將其總計與預期的總計進行比較。In the following example, a series of numbers are added together, and their total is compared with their expected total. 雖然兩個值看起來是相同的,但呼叫 Equals 方法會指出它們不是。Although the two values appear to be the same, a call to the Equals method indicates that they are not.

    using System;
    
    public class Example
    {
       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 ({0}) does not equal the total ({1}).",
                               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 Example
       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).   
    

    如果您將 Console.WriteLine(String, Object, Object) 語句中的格式專案從 {0}{1} 變更為 {0:R},並 {1:R} 顯示兩個 Double 值的所有有效位數,則表示兩個值不相等,因為精確度遺失在新增作業期間。If you change the format items in the Console.WriteLine(String, Object, Object) statement from {0} and {1} to {0:R} and {1:R} to display all significant digits of the two Double values, it is clear that the two values are unequal because of a loss of precision during the addition operations. 在此情況下,您可以藉由呼叫 Math.Round(Double, Int32) 方法,將 Double 值舍入為所需的精確度,然後再執行比較,來解決此問題。In this case, the issue can be resolved by calling the Math.Round(Double, Int32) method to round the Double values to the desired precision before performing the comparison.

  • 如果使用十進位數,使用浮點數的數學或比較運算可能不會產生相同的結果,因為二進位浮點數可能不等於十進位數。A mathematical or comparison operation that uses a floating-point number might not yield the same result if a decimal number is used, because the binary floating-point number might not equal the decimal number. 先前的範例會顯示將 .1 乘以10並加上1次的結果,以說明這一點。A previous example illustrated this by displaying the result of multiplying .1 by 10 and adding .1 times.

    當數值運算中具有小數值的精確度很重要時,您可以使用 Decimal,而不是 Double 類型。When accuracy in numeric operations with fractional values is important, you can use the Decimal rather than the Double type. 如果數值運算中的整數值在 Int64UInt64 類型的範圍外,其精確度很重要,請使用 BigInteger 類型。When accuracy in numeric operations with integral values beyond the range of the Int64 or UInt64 types is important, use the BigInteger type.

  • 如果涉及浮點數,值可能不會往返。A value might not round-trip if a floating-point number is involved. 如果作業將原始浮點數轉換成另一種形式,則會將值稱為來回行程,反向運算會將轉換後的表單轉換回浮點數,而最後的浮點數則不等於原始的浮點數字。A value is said to round-trip if an operation converts an original floating-point number to another form, an inverse operation transforms the converted form back to a floating-point number, and the final floating-point number is not equal to the original floating-point number. 來回行程可能會失敗,因為轉換中遺失或變更了一或多個最不重要的數位。The round trip might fail because one or more least significant digits are lost or changed in a conversion. 在下列範例中,會將三個 Double 值轉換成字串,並儲存在檔案中。In the following example, three Double values are converted to strings and saved in a file. 不過,如輸出所示,雖然值似乎相同,但還原的值不等於原始值。As the output shows, however, even though the values appear to be identical, the restored values are not equal to the original values.

    using System;
    using System.IO;
    
    public class Example
    {
       public static void Main()
       {
          StreamWriter sw = new StreamWriter(@".\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 StreamReader(@".\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("{0} {2} {1}", values[ctr], 
                               restoredValues[ctr],
                               values[ctr].Equals(restoredValues[ctr]) ? "=" : "<>");
       }
    }
    // The example displays the following output:
    //       2.17821782178218 <> 2.17821782178218
    //       0.333333333333333 <> 0.333333333333333
    //       3.14159265358979 <> 3.14159265358979
    
    Imports System.IO
    
    Module Example
       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
    

    在此情況下,您可以使用 "G17"標準數值格式字串來保存完整的 Double 值精確度,以成功地進行迴圈,如下列範例所示。In this case, the values can be successfully round-tripped by using the "G17" standard numeric format string to preserve the full precision of Double values, as the following example shows.

    using System;
    using System.IO;
    
    public class Example
    {
       public static void Main()
       {
          StreamWriter sw = new StreamWriter(@".\Doubles.dat");
          Double[] values = { 2.2/1.01, 1.0/3, Math.PI };
          for (int ctr = 0; ctr < values.Length; ctr++) 
             sw.Write("{0:G17}{1}", values[ctr], ctr < values.Length - 1 ? "|" : "" );
    
          sw.Close();
          
          Double[] restoredValues = new Double[values.Length];
          StreamReader sr = new StreamReader(@".\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("{0} {2} {1}", values[ctr], 
                               restoredValues[ctr],
                               values[ctr].Equals(restoredValues[ctr]) ? "=" : "<>");
       }
    }
    // The example displays the following output:
    //       2.17821782178218 = 2.17821782178218
    //       0.333333333333333 = 0.333333333333333
    //       3.14159265358979 = 3.14159265358979
    
    Imports System.IO
    
    Module Example
       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("{0:G17}{1}", values(ctr), 
                      If(ctr < values.Length - 1, "|", ""))
          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
    

重要

Double 值搭配使用時,在某些情況下,"R" 格式規範無法成功地反復存取原始值。When used with a Double value, the "R" format specifier in some cases fails to successfully round-trip the original value. 若要確保 Double 值成功地往返,請使用 "G17" 格式規範。To ensure that Double values successfully round-trip, use the "G17" format specifier.

  • Single 值的精確度比 Double 的值少。Single values have less precision than Double values. 轉換成看似相等 DoubleSingle 值通常不等於 Double 值,因為有效位數的差異。A Single value that is converted to a seemingly equivalent Double often does not equal the Double value because of differences in precision. 在下列範例中,相同除法運算的結果會指派給 DoubleSingle 值。In the following example, the result of identical division operations is assigned to a Double and a Single value. Single 值轉換成 Double之後,這兩個值的比較會顯示兩者不相等。After the Single value is cast to a Double, a comparison of the two values shows that they are unequal.

    using System;
    
    public class Example
    {
       public static void Main()
       {
          Double value1 = 1/3.0;
          Single sValue2 = 1/3.0f;
          Double value2 = (Double) sValue2;
          Console.WriteLine("{0:R} = {1:R}: {2}", value1, value2, 
                                              value1.Equals(value2));
       }
    }
    // The example displays the following output:
    //        0.33333333333333331 = 0.3333333432674408: False
    
    Module Example
       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 方法,讓這兩個值具有相同的有效位數。To avoid this problem, use either the Double in place of the Single data type, or use the Round method so that both values have the same precision.

此外,因為 Double 類型的有效位數遺失,所以平臺的算術和指派 Double 運算結果可能會因平臺而稍有不同。In addition, the result of arithmetic and assignment operations with Double values may differ slightly by platform because of the loss of precision of the Double type. 例如,在 .NET Framework 的32位和64位版本中,指派常值 Double 的結果可能會有所不同。For example, the result of assigning a literal Double value may differ in the 32-bit and 64-bit versions of the .NET Framework. 下列範例說明當常值-4.42330604244772 E-305 和值為-4.42330604244772 E-305 的變數指派給 Double 變數時的這項差異。The following example illustrates this difference when the literal value -4.42330604244772E-305 and a variable whose value is -4.42330604244772E-305 are assigned to a Double variable. 請注意,在此情況下,Parse(String) 方法的結果不會因遺失精確度而受到影響。Note that the result of the Parse(String) method in this case does not suffer from a loss of precision.

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      
Dim value As Double = -4.42330604244772E-305

Dim fromLiteral As Double = -4.42330604244772E-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      

測試是否相等Testing for Equality

若要視為相等,兩個 Double 值必須代表相同的值。To be considered equal, two Double values must represent identical values. 不過,因為值之間的精確度差異,或因為一或兩個值的精確度遺失,所以預期相同的浮點值通常會因為其最小有效位數的差異而不相等。However, because of differences in precision between values, or because of a loss of precision by one or both values, floating-point values that are expected to be identical often turn out to be unequal because of differences in their least significant digits. 因此,呼叫 Equals 方法來判斷兩個值是否相等,或呼叫 CompareTo 方法來判斷兩個 Double 值之間的關聯性,通常會產生非預期的結果。As a result, calls to the Equals method to determine whether two values are equal, or calls to the CompareTo method to determine the relationship between two Double values, often yield unexpected results. 在下列範例中,這很明顯,因為第一個會有15位數的精確度,而第二個則有17個,而這兩個明顯相等的 Double 值會變成不相等。This is evident in the following example, where two apparently equal Double values turn out to be unequal because the first has 15 digits of precision, while the second has 17.

using System;

public class Example
{
   public static void Main()
   {
      double value1 = .333333333333333;
      double value2 = 1.0/3;
      Console.WriteLine("{0:R} = {1:R}: {2}", value1, value2, value1.Equals(value2));
   }
}
// The example displays the following output:
//        0.333333333333333 = 0.33333333333333331: False
Module Example
   Public Sub Main()
      Dim value1 As Double = .333333333333333
      Dim value2 As Double = 1/3
      Console.WriteLine("{0:R} = {1:R}: {2}", value1, value2, value1.Equals(value2))
   End Sub
End Module
' The example displays the following output:
'       0.333333333333333 = 0.33333333333333331: False

遵循不同程式碼路徑,並以不同方式操作的計算值,通常會證明不相等。Calculated values that follow different code paths and that are manipulated in different ways often prove to be unequal. 在下列範例中,其中一個 Double 值為平方,然後計算平方根以還原原始值。In the following example, one Double value is squared, and then the square root is calculated to restore the original value. 第二個 Double 會乘以3.51 和平方,而結果的平方根會除以3.51 以還原原始值。A second Double is multiplied by 3.51 and squared before the square root of the result is divided by 3.51 to restore the original value. 雖然兩個值看起來完全相同,但呼叫 Equals(Double) 方法會指出它們不相等。Although the two values appear to be identical, a call to the Equals(Double) method indicates that they are not equal. 使用 "R" 標準格式字串來傳回結果字串,以顯示每個 Double 值的所有有效位數,顯示第二個值的 .0000000000001 小於第一個。Using the "R" standard format string to return a result string that displays all the significant digits of each Double value shows that the second value is .0000000000001 less than the first.

using System;

public class Example
{
   public static void Main()
   {
      double value1 = 100.10142;
      value1 = Math.Sqrt(Math.Pow(value1, 2));
      double value2 = Math.Pow(value1 * 3.51, 2);
      value2 = Math.Sqrt(value2) / 3.51;
      Console.WriteLine("{0} = {1}: {2}\n", 
                        value1, value2, value1.Equals(value2)); 
      Console.WriteLine("{0:R} = {1:R}", value1, value2); 
   }
}
// The example displays the following output:
//    100.10142 = 100.10142: False
//    
//    100.10142 = 100.10141999999999
Module Example
   Public Sub Main()
      Dim value1 As Double = 100.10142
      value1 = Math.Sqrt(Math.Pow(value1, 2))
      Dim value2 As Double = Math.Pow(value1 * 3.51, 2)
      value2 = Math.Sqrt(value2) / 3.51
      Console.WriteLine("{0} = {1}: {2}", 
                        value1, value2, value1.Equals(value2)) 
      Console.WriteLine()
      Console.WriteLine("{0:R} = {1:R}", value1, value2) 
   End Sub
End Module
' The example displays the following output:
'    100.10142 = 100.10142: False
'    
'    100.10142 = 100.10141999999999

如果遺失精確度可能會影響比較的結果,您可以採用下列任何替代方法來呼叫 EqualsCompareTo 方法:In cases where a loss of precision is likely to affect the result of a comparison, you can adopt any of the following alternatives to calling the Equals or CompareTo method:

  • 呼叫 Math.Round 方法,以確保這兩個值具有相同的有效位數。Call the Math.Round method to ensure that both values have the same precision. 下列範例會修改前一個範例,以使用此方法,讓兩個小數值相等。The following example modifies a previous example to use this approach so that two fractional values are equivalent.

    using System;
    
    public class Example
    {
       public static void Main()
       {
          double value1 = .333333333333333;
          double value2 = 1.0/3;
          int precision = 7;
          value1 = Math.Round(value1, precision);
          value2 = Math.Round(value2, precision);
          Console.WriteLine("{0:R} = {1:R}: {2}", value1, value2, value1.Equals(value2));
       }
    }
    // The example displays the following output:
    //        0.3333333 = 0.3333333: True
    
    Module Example
       Public Sub Main()
          Dim value1 As Double = .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:R} = {1:R}: {2}", value1, value2, value1.Equals(value2))
       End Sub
    End Module
    ' The example displays the following output:
    '       0.3333333 = 0.3333333: True
    

    不過要注意的是,精確度的問題仍然適用于中間值的圓角。Note, though, that the problem of precision still applies to rounding of midpoint values. 如需詳細資訊,請參閱 Math.Round(Double, Int32, MidpointRounding) 方法。For more information, see the Math.Round(Double, Int32, MidpointRounding) method.

  • 測試近似相等,而不是相等。Test for approximate equality rather than equality. 這會要求您定義一個絕對值,讓這兩個值可以不同但仍然相等,或者您定義較小值可以與較大值分離的相對量。This requires that you define either an absolute amount by which the two values can differ but still be equal, or that you define a relative amount by which the smaller value can diverge from the larger value.

    警告

    在測試是否相等時,Double.Epsilon 有時會當做兩個 Double 值之間距離的絕對量值。Double.Epsilon is sometimes used as an absolute measure of the distance between two Double values when testing for equality. 不過,Double.Epsilon 會測量其值為零的 Double 可新增或減去的最小可能值。However, Double.Epsilon measures the smallest possible value that can be added to, or subtracted from, a Double whose value is zero. 對於大部分的正和負 Double 值而言,Double.Epsilon 的值太小,無法偵測出來。For most positive and negative Double values, the value of Double.Epsilon is too small to be detected. 因此,除了零以外的值,我們不建議在測試中使用它來進行相等。Therefore, except for values that are zero, we do not recommend its use in tests for equality.

    下列範例會使用第二個方法來定義 IsApproximatelyEqual 方法,以測試兩個值之間的相對差異。The following example uses the latter approach to define an IsApproximatelyEqual method that tests the relative difference between two values. 它也會對比呼叫 IsApproximatelyEqual 方法和 Equals(Double) 方法的結果。It also contrasts the result of calls to the IsApproximatelyEqual method and the Equals(Double) method.

    using System;
    
    public class Example
    {
       public static void Main()
       {
          double one1 = .1 * 10;
          double one2 = 0;
          for (int ctr = 1; ctr <= 10; ctr++)
             one2 += .1;
    
          Console.WriteLine("{0:R} = {1:R}: {2}", one1, one2, one1.Equals(one2));
          Console.WriteLine("{0:R} is approximately equal to {1:R}: {2}", 
                            one1, 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
    
    Module Example
       Public Sub Main()
          Dim one1 As Double = .1 * 10
          Dim one2 As Double = 0
          For ctr As Integer = 1 To 10
             one2 += .1
          Next
          Console.WriteLine("{0:R} = {1:R}: {2}", one1, one2, one1.Equals(one2))
          Console.WriteLine("{0:R} is approximately equal to {1:R}: {2}", 
                            one1, one2, 
                            IsApproximatelyEqual(one1, one2, .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)
          Else If Double.IsInfinity(value2) Or Double.IsNaN(value2)
             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
    

浮點值和例外狀況Floating-Point Values and Exceptions

與整數類型的作業不同,這種情況會在溢位或不合法作業(例如零除)時擲回例外狀況,具有浮點值的作業不會擲回例外狀況。Unlike operations with integral types, which throw exceptions in cases of overflow or illegal operations such as division by zero, operations with floating-point values do not throw exceptions. 相反地,在例外狀況下,浮點運算的結果為零、正無限大、負無限大或不是數位(NaN):Instead, in exceptional situations, the result of a floating-point operation is zero, positive infinity, negative infinity, or not a number (NaN):

  • 如果浮點運算的結果太小而無法用於目的地格式,則結果會是零。If the result of a floating-point operation is too small for the destination format, the result is zero. 當兩個非常小的數位相乘時,就會發生這種情況,如下列範例所示。This can occur when two very small numbers are multiplied, as the following example shows.

    using System;
    
    public class Example
    {
       public static void Main()
       {
          Double value1 = 1.1632875981534209e-225;
          Double value2 = 9.1642346778e-175;
          Double result = value1 * value2;
          Console.WriteLine("{0} * {1} = {2}", value1, value2, result);
          Console.WriteLine("{0} = 0: {1}", result, result.Equals(0.0));
       }
    }
    // The example displays the following output:
    //       1.16328759815342E-225 * 9.1642346778E-175 = 0
    //       0 = 0: True
    
    Module Example
       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
    
  • 如果浮點運算的結果量超過目的地格式的範圍,則作業的結果會 PositiveInfinityNegativeInfinity(適用于結果的正負號)。If the magnitude of the result of a floating-point operation exceeds the range of the destination format, the result of the operation is PositiveInfinity or NegativeInfinity, as appropriate for the sign of the result. PositiveInfinity溢位 Double.MaxValue 的運算結果,而且會 NegativeInfinity溢位 Double.MinValue 的運算結果,如下列範例所示。The result of an operation that overflows Double.MaxValue is PositiveInfinity, and the result of an operation that overflows Double.MinValue is NegativeInfinity, as the following example shows.

    using System;
    
    public class Example
    {
       public static void Main()
       {
          Double value1 = 4.565e153;
          Double value2 = 6.9375e172;
          Double result = value1 * value2;
          Console.WriteLine("PositiveInfinity: {0}", 
                             Double.IsPositiveInfinity(result));
          Console.WriteLine("NegativeInfinity: {0}\n", 
                            Double.IsNegativeInfinity(result));
    
          value1 = -value1;
          result = value1 * value2;
          Console.WriteLine("PositiveInfinity: {0}", 
                             Double.IsPositiveInfinity(result));
          Console.WriteLine("NegativeInfinity: {0}", 
                            Double.IsNegativeInfinity(result));
       }
    }                                                                 
    
    // The example displays the following output:
    //       PositiveInfinity: True
    //       NegativeInfinity: False
    //       
    //       PositiveInfinity: False
    //       NegativeInfinity: True
    
    Module Example
       Public Sub Main()
          Dim value1 As Double = 4.565e153
          Dim value2 As Double = 6.9375e172
          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 也會由零除和正被除數所造成的結果,並 NegativeInfinity 除數為零的結果,並被除數為負。PositiveInfinity also results from a division by zero with a positive dividend, and NegativeInfinity results from a division by zero with a negative dividend.

  • 如果浮點運算無效,則會 NaN作業的結果。If a floating-point operation is invalid, the result of the operation is NaN. 例如,NaN 來自下列作業的結果:For example, NaN results from the following operations:

  • 任何具有無效輸入的浮點運算。Any floating-point operation with an invalid input. 例如,以負值呼叫 Math.Sqrt 方法會傳回 NaN,如同呼叫 Math.Acos 方法,其值大於1或小於負一。For example, calling the Math.Sqrt method with a negative value returns NaN, as does calling the Math.Acos method with a value that is greater than one or less than negative one.

  • 具有 Double.NaN值之引數的任何運算。Any operation with an argument whose value is Double.NaN.

類型轉換和雙重結構Type conversions and the Double structure

Double 結構不會定義任何明確或隱含的轉換運算子;相反地,轉換是由編譯器來執行。The Double structure does not define any explicit or implicit conversion operators; instead, conversions are implemented by the compiler.

將任何基本數數值型別的值轉換為 Double 是擴輾轉換,因此不需要明確轉換運算子或呼叫轉換方法,除非編譯器明確要求它。The conversion of the value of any primitive numeric type to a Double is a widening conversion and therefore does not require an explicit cast operator or call to a conversion method unless a compiler explicitly requires it. 例如, C#編譯器需要轉型運算子,才能從 Decimal 轉換成 Double,而 Visual Basic 編譯器則否。For example, the C# compiler requires a casting operator for conversions from Decimal to Double, while the Visual Basic compiler does not. 下列範例會將其他基本數數值型別的最小或最大值轉換為 DoubleThe following example converts the minimum or maximum value of other primitive numeric types to a Double.

using System;

public class Example
{
   public static void Main()
   {
      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 (var value in values) {
         if (value.GetType() == typeof(Decimal))
            dblValue = (Double) value;
         else
            dblValue = value;
         Console.WriteLine("{0} ({1}) --> {2:R} ({3})",
                           value, value.GetType().Name,
                           dblValue, 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 Example
   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.NaNSingle.PositiveInfinitySingle.NegativeInfinity 會分別轉換成 Double.NaNDouble.PositiveInfinityDouble.NegativeInfinityIn addition, the Single values Single.NaN, Single.PositiveInfinity, and Single.NegativeInfinity covert to Double.NaN, Double.PositiveInfinity, and Double.NegativeInfinity, respectively.

請注意,某些數數值型別的值轉換成 Double 值可能會遺失有效位數。Note that the conversion of the value of some numeric types to a Double value can involve a loss of precision. 如範例所示,將 DecimalInt64SingleUInt64 值轉換成 Double 值時,可能會失去精確度。As the example illustrates, a loss of precision is possible when converting Decimal, Int64, Single, and UInt64 values to Double values.

Double 值轉換為任何其他基本數值資料類型的值是縮小轉換,而且需要轉換運算子(在中C#為)、轉換方法(在 Visual Basic 中),或對 Convert 方法的呼叫。The conversion of a Double value to a value of any other primitive numeric data type is a narrowing conversion and requires a cast operator (in C#), a conversion method (in Visual Basic), or a call to a Convert method. 目標資料類型的範圍以外的值(由目標型別的 MinValueMaxValue 屬性所定義),其行為如下表所示。Values that are outside the range of the target data type, which are defined by the target type's MinValue and MaxValue properties, behave as shown in the following table.

目標類型Target type 結果Result
任何整數類資料類型Any integral type 如果在檢查的內容中發生轉換,則為 OverflowException 的例外狀況。An OverflowException exception if the conversion occurs in a checked context.

如果轉換發生在未檢查的內容中(的預設C#值),轉換作業將會成功,但值會溢位。If the conversion occurs in an unchecked context (the default in C#), the conversion operation succeeds but the value overflows.
Decimal OverflowException 例外狀況。An OverflowException exception.
Single 負數值的 Single.NegativeInfinitySingle.NegativeInfinity for negative values.

正數值的 Single.PositiveInfinitySingle.PositiveInfinity for positive values.

此外,Double.NaNDouble.PositiveInfinityDouble.NegativeInfinity 會在檢查的內容中擲回轉換成整數的 OverflowException,但是在未檢查的內容中轉換成整數時,這些值會溢位。In addition, Double.NaN, Double.PositiveInfinity, and Double.NegativeInfinity throw an OverflowException for conversions to integers in a checked context, but these values overflow when converted to integers in an unchecked context. 若要轉換為 Decimal,它們一律會擲回 OverflowExceptionFor conversions to Decimal, they always throw an OverflowException. 為了轉換成 Single,它們會分別轉換成 Single.NaNSingle.PositiveInfinitySingle.NegativeInfinityFor conversions to Single, they convert to Single.NaN, Single.PositiveInfinity, and Single.NegativeInfinity, respectively.

請注意,將 Double 值轉換成另一個數數值型別可能會導致失去精確度。Note that a loss of precision may result from converting a Double value to another numeric type. 在轉換非整數 Double 值的情況下,如範例的輸出所示,當 Double 值為圓角(如 Visual Basic)或截斷(如C#)時,分陣列件會遺失。In the case of converting non-integral Double values, as the output from the example shows, the fractional component is lost when the Double value is either rounded (as in Visual Basic) or truncated (as in C#). 若要轉換為 DecimalSingle 值,Double 值在目標資料類型中可能不會有精確的標記法。For conversions to Decimal and Single values, the Double value may not have a precise representation in the target data type.

下列範例會將數個 Double 值轉換成幾個其他數數值型別。The following example converts a number of Double values to several other numeric types. 轉換會在 Visual Basic (預設值)和C# (因為checked關鍵字)中的已檢查內容中發生。The conversions occur in a checked context in Visual Basic (the default) and in C# (because of the checked keyword). 範例的輸出顯示已核取的未檢查內容中的轉換結果。The output from the example shows the result for conversions in both a checked an unchecked context. 您可以在 Visual Basic 中,藉由使用 /removeintchecks+ 編譯器參數和在中C# ,藉由批註化 checked 語句來執行轉換。You can perform conversions in an unchecked context in Visual Basic by compiling with the /removeintchecks+ compiler switch and in C# by commenting out the checked statement.

using System;

public class Example
{
   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("{0} ({1}) --> {2} (0x{2:X16}) ({3})",
                                  value, value.GetType().Name,
                                  lValue, lValue.GetType().Name);
            }
            catch (OverflowException) {
               Console.WriteLine("Unable to convert {0} to Int64.", value);
            }
            try {
                UInt64 ulValue = (ulong) value;
                Console.WriteLine("{0} ({1}) --> {2} (0x{2:X16}) ({3})",
                                  value, value.GetType().Name,
                                  ulValue, ulValue.GetType().Name);
            }
            catch (OverflowException) {
               Console.WriteLine("Unable to convert {0} to UInt64.", value);
            }
            try {
                Decimal dValue = (decimal) value;
                Console.WriteLine("{0} ({1}) --> {2} ({3})",
                                  value, value.GetType().Name,
                                  dValue, dValue.GetType().Name);
            }
            catch (OverflowException) {
               Console.WriteLine("Unable to convert {0} to Decimal.", value);
            }
            try {
                Single sValue = (float) value;
                Console.WriteLine("{0} ({1}) --> {2} ({3})",
                                  value, value.GetType().Name,
                                  sValue, sValue.GetType().Name);
            }
            catch (OverflowException) {
               Console.WriteLine("Unable to convert {0} to Single.", value);
            }
            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)
Module Example
   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)

如需數數值型別轉換的詳細資訊,請參閱 .NET Framework 和類型轉換表中的類型轉換For more information on the conversion of numeric types, see Type Conversion in the .NET Framework and Type Conversion Tables.

浮點功能Floating-Point Functionality

Double 結構和相關類型提供在下欄區域執行作業的方法:The Double structure and related types provide methods to perform operations in the following areas:

  • 值的比較Comparison of values. 您可以呼叫 Equals 方法來判斷兩個 Double 值是否相等,或 CompareTo 方法來判斷兩個值之間的關聯性。You can call the Equals method to determine whether two Double values are equal, or the CompareTo method to determine the relationship between two values.

    Double 結構也支援一組完整的比較運算子。The Double structure also supports a complete set of comparison operators. 例如,您可以測試是否相等或不等比較,或判斷某個值是否大於或等於另一個值。For example, you can test for equality or inequality, or determine whether one value is greater than or equal to another. 如果其中一個運算元是 Double以外的數數值型別,則會先將它轉換成 Double,然後再執行比較。If one of the operands is a numeric type other than a Double, it is converted to a Double before performing the comparison.

    警告

    因為精確度的差異,您預期相等的兩個 Double 值可能會變成不相等,這會影響比較的結果。Because of differences in precision, two Double values that you expect to be equal may turn out to be unequal, which affects the result of the comparison. 如需比較兩個 Double 值的詳細資訊,請參閱測試相等一節。See the Testing for Equality section for more information about comparing two Double values.

    您也可以呼叫 IsNaNIsInfinityIsPositiveInfinityIsNegativeInfinity 方法來測試這些特殊值。You can also call the IsNaN, IsInfinity, IsPositiveInfinity, and IsNegativeInfinity methods to test for these special values.

  • 數學運算Mathematical operations. 一般算數運算(例如加法、減法、乘法和除法)是由語言編譯器和一般中繼語言(CIL)指示來執行,而不是透過 Double 方法。Common arithmetic operations, such as addition, subtraction, multiplication, and division, are implemented by language compilers and Common Intermediate Language (CIL) instructions, rather than by Double methods. 如果數學運算中的其中一個運算元是 Double以外的數數值型別,則會先將它轉換成 Double,然後再執行作業。If one of the operands in a mathematical operation is a numeric type other than a Double, it is converted to a Double before performing the operation. 運算的結果也是 Double 值。The result of the operation is also a Double value.

    藉由呼叫 System.Math 類別中的 staticShared Visual Basic)方法,可以執行其他數學運算。Other mathematical operations can be performed by calling static (Shared in Visual Basic) methods in the System.Math class. 其中包含常用於算術的其他方法(例如 Math.AbsMath.SignMath.Sqrt)、geometry (例如 Math.CosMath.Sin)和微積分(例如 Math.Log)。It includes additional methods commonly used for arithmetic (such as Math.Abs, Math.Sign, and Math.Sqrt), geometry (such as Math.Cos and Math.Sin), and calculus (such as Math.Log).

    您也可以在 Double 值中操作個別位。You can also manipulate the individual bits in a Double value. BitConverter.DoubleToInt64Bits 方法會在64位整數中保留 Double 值的位模式。The BitConverter.DoubleToInt64Bits method preserves a Double value's bit pattern in a 64-bit integer. BitConverter.GetBytes(Double) 方法會在位元組陣列中傳回其位模式。The BitConverter.GetBytes(Double) method returns its bit pattern in a byte array.

  • 進位Rounding. 進位通常用來做為減少因浮點標記法和精確度問題而造成之值差異的技術。Rounding is often used as a technique for reducing the impact of differences between values caused by problems of floating-point representation and precision. 您可以藉由呼叫 Math.Round 方法來四捨五入 Double 值。You can round a Double value by calling the Math.Round method.

  • 格式Formatting. 您可以藉由呼叫 ToString 方法或使用複合格式功能,將 Double 值轉換為其字串表示。You can convert a Double value to its string representation by calling the ToString method or by using the composite formatting feature. 如需格式字串如何控制浮點值的字串標記法的詳細資訊,請參閱標準數值格式字串自訂數值格式字串主題。For information about how format strings control the string representation of floating-point values, see the Standard Numeric Format Strings and Custom Numeric Format Strings topics.

  • 剖析字串Parsing strings. 您可以藉由呼叫 ParseTryParse 方法,將浮點值的字串表示轉換為 Double 值。You can convert the string representation of a floating-point value to a Double value by calling either the Parse or TryParse method. 如果剖析作業失敗,Parse 方法會擲回例外狀況,而 TryParse 方法會傳回 falseIf the parse operation fails, the Parse method throws an exception, whereas the TryParse method returns false.

  • 類型轉換Type conversion. Double 結構會針對 IConvertible 介面提供明確的介面實作為,支援在任何兩個標準 .NET Framework 資料類型之間進行轉換。The Double structure provides an explicit interface implementation for the IConvertible interface, which supports conversion between any two standard .NET Framework data types. 語言編譯器也支援將所有其他標準數數值型別的值隱含轉換成 Double 值。Language compilers also support the implicit conversion of values of all other standard numeric types to Double values. 將任何標準數數值型別的值轉換為 Double 是擴輾轉換,而且不需要轉換運算子或轉換方法的使用者。Conversion of a value of any standard numeric type to a Double is a widening conversion and does not require the user of a casting operator or conversion method,

    不過,Int64Single 值的轉換可能會遺失有效位數。However, conversion of Int64 and Single values can involve a loss of precision. 下表列出每種類型的精確度差異:The following table lists the differences in precision for each of these types:

    類型Type 最大有效位數Maximum precision 內部有效位數Internal precision
    Double 1515 1717
    Int64 19個小數位數19 decimal digits 19個小數位數19 decimal digits
    Single 7個小數位數7 decimal digits 9個小數位數9 decimal digits

    有效位數的問題最常影響轉換成 DoubleSingle 值。The problem of precision most frequently affects Single values that are converted to Double values. 在下列範例中,相同除法運算所產生的兩個值不相等,因為其中一個值是轉換成 Double的單精確度浮點值。In the following example, two values produced by identical division operations are unequal because one of the values is a single-precision floating point value converted to a Double.

    using System;
    
    public class Example
    {
       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:           {0:R}", result1);
          Console.WriteLine(".1 Added 10 times: {0:R}", result2);
       }
    }
    // The example displays the following output:
    //       .1 * 10:           1
    //       .1 Added 10 times: 0.99999999999999989
    
    Module Example
       Public Sub Main()
          Dim value As Double = .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
    

欄位

Epsilon

代表大於零的最小正 Double 值。Represents the smallest positive Double value that is greater than zero. 這個欄位是常數。This field is constant.

MaxValue

表示 Double 最大的可能值。Represents the largest possible value of a Double. 這個欄位是常數。This field is constant.

MinValue

表示 Double 最小的可能值。Represents the smallest possible value of a Double. 這個欄位是常數。This field is constant.

NaN

代表不是數字 (NaN) 的值。Represents a value that is not a number (NaN). 這個欄位是常數。This field is constant.

NegativeInfinity

表示負無限大。Represents negative infinity. 這個欄位是常數。This field is constant.

PositiveInfinity

表示正無限大。Represents positive infinity. 這個欄位是常數。This field is constant.

方法

CompareTo(Double)

比較這個執行個體與雙精確度的浮點數值,並且傳回一個整數,指出這個執行個體的值是小於、等於或大於特定的雙精確度浮點數值。Compares this instance to a specified double-precision floating-point number and returns an integer that indicates whether the value of this instance is less than, equal to, or greater than the value of the specified double-precision floating-point number.

CompareTo(Object)

比較這個執行個體與特定物件,並且傳回一個整數,指出這個執行個體的值是小於、等於或大於特定物件的值。Compares this instance to a specified object and returns an integer that indicates whether the value of this instance is less than, equal to, or greater than the value of the specified object.

Equals(Double)

傳回數值,指示這個執行個體和指定的 Double 物件是否表示相同的值。Returns a value indicating whether this instance and a specified Double object represent the same value.

Equals(Object)

傳回值,指出這個執行個體 (Instance) 是否和指定的物件相等。Returns a value indicating whether this instance is equal to a specified object.

GetHashCode()

傳回這個執行個體的雜湊碼。Returns the hash code for this instance.

GetTypeCode()

傳回實值類型 TypeCodeDoubleReturns the TypeCode for value type Double.

IsFinite(Double)

判斷指定的值是否為有限 (零、偏低或一般)。Determines whether the specified value is finite (zero, subnormal, or normal).

IsInfinity(Double)

傳回值,指出指定的數字是否計算結果為負或正的無限大。Returns a value indicating whether the specified number evaluates to negative or positive infinity.

IsNaN(Double)

傳回值,這個值表示指定的值是否不是數字 (NaN)。Returns a value that indicates whether the specified value is not a number (NaN).

IsNegative(Double)

判斷指定的值是否為負數。Determines whether the specified value is negative.

IsNegativeInfinity(Double)

傳回值,指出指定的數字是否計算結果為負的無限大。Returns a value indicating whether the specified number evaluates to negative infinity.

IsNormal(Double)

判斷指定的值是否為正常。Determines whether the specified value is normal.

IsPositiveInfinity(Double)

傳回值,指出指定數字是否計算結果為正的無限大。Returns a value indicating whether the specified number evaluates to positive infinity.

IsSubnormal(Double)

判斷指定的值是否為偏低。Determines whether the specified value is subnormal.

Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider)

將包含數字字串表示 (使用指定樣式和特定文化特性格式) 的字元範圍轉換為其對等的雙精確度浮點數。Converts a character span that contains the string representation of a number in a specified style and culture-specific format to its double-precision floating-point number equivalent.

Parse(String)

將數字的字串表示轉換為其相等的雙精確度浮點數。Converts the string representation of a number to its double-precision floating-point number equivalent.

Parse(String, IFormatProvider)

將數字的字串表示 (使用指定的特定文化特性格式) 轉換為其相等的雙精確度浮點數。Converts the string representation of a number in a specified culture-specific format to its double-precision floating-point number equivalent.

Parse(String, NumberStyles)

將數字的字串表示 (使用指定樣式) 轉換為其相等的雙精確度浮點數。Converts the string representation of a number in a specified style to its double-precision floating-point number equivalent.

Parse(String, NumberStyles, IFormatProvider)

使用指定樣式和特定文化特性格式,將數字的字串表示轉換為其相等的雙精確度浮點數。Converts the string representation of a number in a specified style and culture-specific format to its double-precision floating-point number equivalent.

ToString()

將這個執行個體的數值轉換為它的相等字串表示。Converts the numeric value of this instance to its equivalent string representation.

ToString(IFormatProvider)

使用指定的特定文化特性格式資訊,將這個執行個體的數值轉換成它的相等字串表示。Converts the numeric value of this instance to its equivalent string representation using the specified culture-specific format information.

ToString(String)

使用指定格式,將這個執行個體的數值轉換成它的相等字串表示。Converts the numeric value of this instance to its equivalent string representation, using the specified format.

ToString(String, IFormatProvider)

使用指定的格式和特定文化特性格式資訊,將這個執行個體的數值轉換成它的相等字串表示。Converts the numeric value of this instance to its equivalent string representation using the specified format and culture-specific format information.

TryFormat(Span<Char>, Int32, ReadOnlySpan<Char>, IFormatProvider)

嘗試將目前雙精確度浮點數執行個體的值格式化為所提供的字元範圍。Tries to format the value of the current double instance into the provided span of characters.

TryParse(ReadOnlySpan<Char>, Double)

將數字的範圍表示 (使用指定樣式和特定文化特性格式) 轉換為其對等的雙精確度浮點數。Converts the span representation of a number in a specified style and culture-specific format to its double-precision floating-point number equivalent. 傳回值會指出轉換成功或失敗。A return value indicates whether the conversion succeeded or failed.

TryParse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider, Double)

將包含數字字串表示 (使用指定樣式和特定文化特性格式) 的字元範圍轉換為其對等的雙精確度浮點數。Converts a character span containing the string representation of a number in a specified style and culture-specific format to its double-precision floating-point number equivalent. 傳回值會指出轉換成功或失敗。A return value indicates whether the conversion succeeded or failed.

TryParse(String, Double)

將數字的字串表示轉換為其相等的雙精確度浮點數。Converts the string representation of a number to its double-precision floating-point number equivalent. 傳回值會指出轉換成功或失敗。A return value indicates whether the conversion succeeded or failed.

TryParse(String, NumberStyles, IFormatProvider, Double)

使用指定樣式和特定文化特性格式,將數字的字串表示轉換為其相等的雙精確度浮點數。Converts the string representation of a number in a specified style and culture-specific format to its double-precision floating-point number equivalent. 傳回值會指出轉換成功或失敗。A return value indicates whether the conversion succeeded or failed.

運算子

Equality(Double, Double)

傳回值,這個值表示兩個指定的 Double 值是否相等。Returns a value that indicates whether two specified Double values are equal.

GreaterThan(Double, Double)

傳回值,這個值表示指定的 Double 值是否大於另一個指定的 Double 值。Returns a value that indicates whether a specified Double value is greater than another specified Double value.

GreaterThanOrEqual(Double, Double)

傳回值,這個值表示指定的 Double 值是否大於或等於另一個指定的 Double 值。Returns a value that indicates whether a specified Double value is greater than or equal to another specified Double value.

Inequality(Double, Double)

傳回值,這個值表示兩個指定的 Double 值是否不相等。Returns a value that indicates whether two specified Double values are not equal.

LessThan(Double, Double)

傳回值,這個值表示指定的 Double 值是否小於另一個指定的 Double 值。Returns a value that indicates whether a specified Double value is less than another specified Double value.

LessThanOrEqual(Double, Double)

傳回值,這個值表示指定的 Double 值是否小於或等於另一個指定的 Double 值。Returns a value that indicates whether a specified Double value is less than or equal to another specified Double value.

明確介面實作

IComparable.CompareTo(Object)
IConvertible.GetTypeCode()
IConvertible.ToBoolean(IFormatProvider)

如需這個成員的說明,請參閱 ToBoolean(IFormatProvider)For a description of this member, see ToBoolean(IFormatProvider).

IConvertible.ToByte(IFormatProvider)

如需這個成員的說明,請參閱 ToByte(IFormatProvider)For a description of this member, see ToByte(IFormatProvider).

IConvertible.ToChar(IFormatProvider)

不支援這個轉換。This conversion is not supported. 嘗試使用這個方法會擲回 InvalidCastExceptionAttempting to use this method throws an InvalidCastException.

IConvertible.ToDateTime(IFormatProvider)

不支援這個轉換。This conversion is not supported. 嘗試使用這個方法會擲回 InvalidCastExceptionAttempting to use this method throws an InvalidCastException

IConvertible.ToDecimal(IFormatProvider)

如需這個成員的說明,請參閱 ToDecimal(IFormatProvider)For a description of this member, see ToDecimal(IFormatProvider).

IConvertible.ToDouble(IFormatProvider)

如需這個成員的說明,請參閱 ToDouble(IFormatProvider)For a description of this member, see ToDouble(IFormatProvider).

IConvertible.ToInt16(IFormatProvider)

如需這個成員的說明,請參閱 ToInt16(IFormatProvider)For a description of this member, see ToInt16(IFormatProvider).

IConvertible.ToInt32(IFormatProvider)

如需這個成員的說明,請參閱 ToInt32(IFormatProvider)For a description of this member, see ToInt32(IFormatProvider).

IConvertible.ToInt64(IFormatProvider)

如需這個成員的說明,請參閱 ToInt64(IFormatProvider)For a description of this member, see ToInt64(IFormatProvider).

IConvertible.ToSByte(IFormatProvider)

如需這個成員的說明,請參閱 ToSByte(IFormatProvider)For a description of this member, see ToSByte(IFormatProvider).

IConvertible.ToSingle(IFormatProvider)

如需這個成員的說明,請參閱 ToSingle(IFormatProvider)For a description of this member, see ToSingle(IFormatProvider).

IConvertible.ToType(Type, IFormatProvider)

如需這個成員的說明,請參閱 ToType(Type, IFormatProvider)For a description of this member, see ToType(Type, IFormatProvider).

IConvertible.ToUInt16(IFormatProvider)

如需這個成員的說明,請參閱 ToUInt16(IFormatProvider)For a description of this member, see ToUInt16(IFormatProvider).

IConvertible.ToUInt32(IFormatProvider)

如需這個成員的說明,請參閱 ToUInt32(IFormatProvider)For a description of this member, see ToUInt32(IFormatProvider).

IConvertible.ToUInt64(IFormatProvider)

如需這個成員的說明,請參閱 ToUInt64(IFormatProvider)For a description of this member, see ToUInt64(IFormatProvider).

適用於

執行緒安全性

此類型的所有成員都是安全線程。All members of this type are thread safe. 出現在修改實例狀態的成員實際上會傳回以新值初始化的新實例。Members that appear to modify instance state actually return a new instance initialized with the new value. 如同任何其他類型,讀取和寫入包含此類型之實例的共用變數必須受到鎖定保護,以確保執行緒安全性。As with any other type, reading and writing to a shared variable that contains an instance of this type must be protected by a lock to guarantee thread safety.

另請參閱