Double Double Double Double Struct

定义

表示一个双精度浮点数。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:The 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.79769313486232e308 到正 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). 它旨在表示值是否 (例如行星或星系之间的距离) 极大或非常小 (千克物质的分子的大容量),通常是并不精确 (如从到的距离地球另一个太阳系),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
指数Exponent 52-6252-62
登录 (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,其通过.1 用一个十进制小数精确地表示为二进制分数,使用模式"0011"重复向无穷远的.001100110011 由表示。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 九次,我们看到此添加,因为它涉及对将八个更多操作,生成不太精确的结果。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. 请注意,仅当我们显示两个明显这种不一致Double通过使用"R"的值标准数字格式字符串,后者如果必要时将显示所有 17 位精度支持Double类型。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和 1 千万亿到它。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. 一个Single值转换为看似等效Double通常不等于Double由于差异精度的值。A Single value that is converted to a seemingly equivalent Double often does not equal the Double value because of differences in precision. 在以下示例中,相同的除法运算的结果分配给Double和一个Single值。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. 例如,分配文本的结果Double值可能不同.NET Framework 的 32 位和 64 位版本。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. 这是很明显的以下示例中,其中两个显然等于Double值会是因为第一个具有 15 位精度,而第二个有 17 个不相等。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"标准格式字符串返回显示的每个双精度值的所有有效位的结果字符串显示第二个值为.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. 溢出的操作结果Double.MaxValuePositiveInfinity,和溢出操作的结果Double.MinValueNegativeInfinity,如下面的示例所示。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.

  • 如果浮点运算无效,该操作的结果是NaNIf 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.NaNAny operation with an argument whose value is Double.NaN.

类型转换和 Double 结构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# 编译器从转换需要强制转换运算符DecimalDouble,而 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.PositiveInfinity,和Single.NegativeInfinity到隐蔽Double.NaNDouble.PositiveInfinity,和Double.NegativeInfinity分别。In 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. 如示例所示,转换时,为可能丢失精度DecimalInt64Single,和UInt64值到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异常,则转换发生在 checked 上下文中。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.NegativeInfinity 对于负值。Single.NegativeInfinity for negative values.

Single.PositiveInfinity 对于正值。Single.PositiveInfinity for positive values.

此外, Double.NaNDouble.PositiveInfinity,并Double.NegativeInfinity引发OverflowException转换成在 checked 的上下文中,但这些值溢出时未检查的上下文中转换成整数的整数。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.PositiveInfinity,和Single.NegativeInfinity分别。For 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# 中检查的上下文中发生的转换 (由于检查关键字)。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.

    您还可以调用IsNaNIsInfinityIsPositiveInfinity,和IsNegativeInfinity方法来测试这些特殊值。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.

    可以通过调用执行其他数学运算static(Shared在 Visual Basic 中) 中的方法System.Math类。Other mathematical operations can be performed by calling static (Shared in Visual Basic) methods in the System.Math class. 它提供了其他方法通常用于进行算术运算 (如Math.AbsMath.Sign,并Math.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方法保留Double值的位模式在 64 位整数。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. 可以舍入Double值通过调用Math.Round方法。You can round a Double value by calling the Math.Round method.

  • 格式设置Formatting. 可以将转换Double值为通过调用其字符串表示形式ToString方法或通过使用复合格式设置功能。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. 可以将转换为浮点值的字符串表示形式Double值通过调用ParseTryParse方法。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

    精度问题最频繁影响Single值转换为Double值。The problem of precision most frequently affects Single values that are converted to Double values. 在以下示例中,生成的相同除法运算的两个值不相等的值之一是单精度浮点值转换为DoubleIn 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 Epsilon Epsilon Epsilon

表示大于零的最小正 Double 值。Represents the smallest positive Double value that is greater than zero. 此字段为常数。This field is constant.

MaxValue MaxValue MaxValue MaxValue

表示 Double 的最大可能值。Represents the largest possible value of a Double. 此字段为常数。This field is constant.

MinValue MinValue MinValue MinValue

表示 Double 的最小可能值。Represents the smallest possible value of a Double. 此字段为常数。This field is constant.

NaN NaN NaN NaN

表示不是数字 (NaN) 的值。Represents a value that is not a number (NaN). 此字段为常数。This field is constant.

NegativeInfinity NegativeInfinity NegativeInfinity NegativeInfinity

表示负无穷。Represents negative infinity. 此字段为常数。This field is constant.

PositiveInfinity PositiveInfinity PositiveInfinity PositiveInfinity

表示正无穷。Represents positive infinity. 此字段为常数。This field is constant.

方法

CompareTo(Double) CompareTo(Double) CompareTo(Double) 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) CompareTo(Object) CompareTo(Object) 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) Equals(Double) Equals(Double) Equals(Double)

返回一个值,该值指示此实例和指定的 Double 对象是否表示相同的值。Returns a value indicating whether this instance and a specified Double object represent the same value.

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

返回一个值,该值指示此实例是否等于指定的对象。Returns a value indicating whether this instance is equal to a specified object.

GetHashCode() GetHashCode() GetHashCode() GetHashCode()

返回此实例的哈希代码。Returns the hash code for this instance.

GetTypeCode() GetTypeCode() GetTypeCode() GetTypeCode()

返回值类型 TypeCodeDoubleReturns the TypeCode for value type Double.

IsFinite(Double) IsFinite(Double) IsFinite(Double) IsFinite(Double)
IsInfinity(Double) IsInfinity(Double) IsInfinity(Double) IsInfinity(Double)

返回一个值,该值指示指定数字是计算为负无穷大还是正无穷大。Returns a value indicating whether the specified number evaluates to negative or positive infinity

IsNaN(Double) IsNaN(Double) IsNaN(Double) IsNaN(Double)

返回一个值,该值指示指定的值是否不为数字 (NaN)。Returns a value that indicates whether the specified value is not a number (NaN).

IsNegative(Double) IsNegative(Double) IsNegative(Double) IsNegative(Double)
IsNegativeInfinity(Double) IsNegativeInfinity(Double) IsNegativeInfinity(Double) IsNegativeInfinity(Double)

返回一个值,通过该值指示指定数字是否计算为负无穷大。Returns a value indicating whether the specified number evaluates to negative infinity.

IsNormal(Double) IsNormal(Double) IsNormal(Double) IsNormal(Double)
IsPositiveInfinity(Double) IsPositiveInfinity(Double) IsPositiveInfinity(Double) IsPositiveInfinity(Double)

返回一个值,通过该值指示指定数字是否计算为正无穷大。Returns a value indicating whether the specified number evaluates to positive infinity.

IsSubnormal(Double) IsSubnormal(Double) IsSubnormal(Double) IsSubnormal(Double)
Parse(String, NumberStyles, IFormatProvider) Parse(String, NumberStyles, IFormatProvider) Parse(String, NumberStyles, IFormatProvider) 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.

Parse(String, IFormatProvider) Parse(String, IFormatProvider) Parse(String, IFormatProvider) 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(ReadOnlySpan<Char>, NumberStyles, IFormatProvider) Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider) Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider) Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider)
Parse(String) Parse(String) Parse(String) Parse(String)

将数字的字符串表示形式转换为它的等效双精度浮点数。Converts the string representation of a number to its double-precision floating-point number equivalent.

Parse(String, NumberStyles) Parse(String, NumberStyles) Parse(String, NumberStyles) Parse(String, NumberStyles)

将指定样式的数字的字符串表示形式转换为它的等效双精度浮点数。Converts the string representation of a number in a specified style to its double-precision floating-point number equivalent.

ToString(String, IFormatProvider) ToString(String, IFormatProvider) ToString(String, IFormatProvider) ToString(String, IFormatProvider)

使用指定的格式和区域性特定格式信息,将此实例的数值转换为它的等效字符串表示形式。Converts the numeric value of this instance to its equivalent string representation using the specified format and culture-specific format information.

ToString(String) ToString(String) ToString(String) ToString(String)

使用指定的格式,将此实例的数值转换为它的等效字符串表示形式。Converts the numeric value of this instance to its equivalent string representation, using the specified format.

ToString(IFormatProvider) ToString(IFormatProvider) ToString(IFormatProvider) ToString(IFormatProvider)

使用指定的区域性特定格式信息,将此实例的数值转换为它的等效字符串表示形式。Converts the numeric value of this instance to its equivalent string representation using the specified culture-specific format information.

ToString() ToString() ToString() ToString()

将此实例的数值转换为其等效的字符串表示形式。Converts the numeric value of this instance to its equivalent string representation.

TryFormat(Span<Char>, Int32, ReadOnlySpan<Char>, IFormatProvider) TryFormat(Span<Char>, Int32, ReadOnlySpan<Char>, IFormatProvider) TryFormat(Span<Char>, Int32, ReadOnlySpan<Char>, IFormatProvider) TryFormat(Span<Char>, Int32, ReadOnlySpan<Char>, IFormatProvider)
TryParse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider, Double) TryParse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider, Double) TryParse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider, Double) TryParse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider, Double)
TryParse(String, Double) TryParse(String, Double) TryParse(String, Double) 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(ReadOnlySpan<Char>, Double) TryParse(ReadOnlySpan<Char>, Double) TryParse(ReadOnlySpan<Char>, Double) TryParse(ReadOnlySpan<Char>, Double)
TryParse(String, NumberStyles, IFormatProvider, Double) TryParse(String, NumberStyles, IFormatProvider, Double) TryParse(String, NumberStyles, IFormatProvider, Double) 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) Equality(Double, Double) Equality(Double, Double) Equality(Double, Double)

返回一个值,该值指示两个指定的 Double 值是否相等。Returns a value that indicates whether two specified Double values are equal.

GreaterThan(Double, Double) GreaterThan(Double, Double) GreaterThan(Double, Double) 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) GreaterThanOrEqual(Double, Double) GreaterThanOrEqual(Double, Double) 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) Inequality(Double, Double) Inequality(Double, Double) Inequality(Double, Double)

返回一个值,该值指示两个指定的 Double 值是否不相等。Returns a value that indicates whether two specified Double values are not equal.

LessThan(Double, Double) LessThan(Double, Double) LessThan(Double, Double) 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) LessThanOrEqual(Double, Double) LessThanOrEqual(Double, Double) 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) IComparable.CompareTo(Object) IComparable.CompareTo(Object) IComparable.CompareTo(Object)
IConvertible.GetTypeCode() IConvertible.GetTypeCode() IConvertible.GetTypeCode() IConvertible.GetTypeCode()
IConvertible.ToBoolean(IFormatProvider) IConvertible.ToBoolean(IFormatProvider) IConvertible.ToBoolean(IFormatProvider) IConvertible.ToBoolean(IFormatProvider)

有关此成员的说明,请参见 ToBoolean(IFormatProvider)For a description of this member, see ToBoolean(IFormatProvider).

IConvertible.ToByte(IFormatProvider) IConvertible.ToByte(IFormatProvider) IConvertible.ToByte(IFormatProvider) IConvertible.ToByte(IFormatProvider)

有关此成员的说明,请参见 ToByte(IFormatProvider)For a description of this member, see ToByte(IFormatProvider).

IConvertible.ToChar(IFormatProvider) IConvertible.ToChar(IFormatProvider) IConvertible.ToChar(IFormatProvider) IConvertible.ToChar(IFormatProvider)

不支持此转换。This conversion is not supported. 尝试使用此方法将引发 InvalidCastExceptionAttempting to use this method throws an InvalidCastException.

IConvertible.ToDateTime(IFormatProvider) IConvertible.ToDateTime(IFormatProvider) IConvertible.ToDateTime(IFormatProvider) IConvertible.ToDateTime(IFormatProvider)

不支持此转换。This conversion is not supported. 尝试使用此方法将引发 InvalidCastExceptionAttempting to use this method throws an InvalidCastException

IConvertible.ToDecimal(IFormatProvider) IConvertible.ToDecimal(IFormatProvider) IConvertible.ToDecimal(IFormatProvider) IConvertible.ToDecimal(IFormatProvider)

有关此成员的说明,请参见 ToDecimal(IFormatProvider)For a description of this member, see ToDecimal(IFormatProvider).

IConvertible.ToDouble(IFormatProvider) IConvertible.ToDouble(IFormatProvider) IConvertible.ToDouble(IFormatProvider) IConvertible.ToDouble(IFormatProvider)

有关此成员的说明,请参见 ToDouble(IFormatProvider)For a description of this member, see ToDouble(IFormatProvider).

IConvertible.ToInt16(IFormatProvider) IConvertible.ToInt16(IFormatProvider) IConvertible.ToInt16(IFormatProvider) IConvertible.ToInt16(IFormatProvider)

有关此成员的说明,请参见 ToInt16(IFormatProvider)For a description of this member, see ToInt16(IFormatProvider).

IConvertible.ToInt32(IFormatProvider) IConvertible.ToInt32(IFormatProvider) IConvertible.ToInt32(IFormatProvider) IConvertible.ToInt32(IFormatProvider)

有关此成员的说明,请参见 ToInt32(IFormatProvider)For a description of this member, see ToInt32(IFormatProvider).

IConvertible.ToInt64(IFormatProvider) IConvertible.ToInt64(IFormatProvider) IConvertible.ToInt64(IFormatProvider) IConvertible.ToInt64(IFormatProvider)

有关此成员的说明,请参见 ToInt64(IFormatProvider)For a description of this member, see ToInt64(IFormatProvider).

IConvertible.ToSByte(IFormatProvider) IConvertible.ToSByte(IFormatProvider) IConvertible.ToSByte(IFormatProvider) IConvertible.ToSByte(IFormatProvider)

有关此成员的说明,请参见 ToSByte(IFormatProvider)For a description of this member, see ToSByte(IFormatProvider).

IConvertible.ToSingle(IFormatProvider) IConvertible.ToSingle(IFormatProvider) IConvertible.ToSingle(IFormatProvider) IConvertible.ToSingle(IFormatProvider)

有关此成员的说明,请参见 ToSingle(IFormatProvider)For a description of this member, see ToSingle(IFormatProvider).

IConvertible.ToType(Type, IFormatProvider) IConvertible.ToType(Type, IFormatProvider) IConvertible.ToType(Type, IFormatProvider) IConvertible.ToType(Type, IFormatProvider)

有关此成员的说明,请参见 ToType(Type, IFormatProvider)For a description of this member, see ToType(Type, IFormatProvider).

IConvertible.ToUInt16(IFormatProvider) IConvertible.ToUInt16(IFormatProvider) IConvertible.ToUInt16(IFormatProvider) IConvertible.ToUInt16(IFormatProvider)

有关此成员的说明,请参见 ToUInt16(IFormatProvider)For a description of this member, see ToUInt16(IFormatProvider).

IConvertible.ToUInt32(IFormatProvider) IConvertible.ToUInt32(IFormatProvider) IConvertible.ToUInt32(IFormatProvider) IConvertible.ToUInt32(IFormatProvider)

有关此成员的说明,请参见 ToUInt32(IFormatProvider)For a description of this member, see ToUInt32(IFormatProvider).

IConvertible.ToUInt64(IFormatProvider) IConvertible.ToUInt64(IFormatProvider) IConvertible.ToUInt64(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.

另请参阅