Double 結構

定義

表示雙精度浮點數。

public value class double : IComparable, IComparable<double>, IConvertible, IEquatable<double>, IFormattable
public value class double : IComparable, IComparable<double>, IConvertible, IEquatable<double>, ISpanFormattable
public value class double : IComparable<double>, IConvertible, IEquatable<double>, IParsable<double>, ISpanParsable<double>, System::Numerics::IAdditionOperators<double, double, double>, System::Numerics::IAdditiveIdentity<double, double>, System::Numerics::IBinaryFloatingPointIeee754<double>, System::Numerics::IBinaryNumber<double>, System::Numerics::IBitwiseOperators<double, double, double>, System::Numerics::IComparisonOperators<double, double, bool>, System::Numerics::IDecrementOperators<double>, System::Numerics::IDivisionOperators<double, double, double>, System::Numerics::IEqualityOperators<double, double, bool>, System::Numerics::IExponentialFunctions<double>, System::Numerics::IFloatingPoint<double>, System::Numerics::IFloatingPointConstants<double>, System::Numerics::IFloatingPointIeee754<double>, System::Numerics::IHyperbolicFunctions<double>, System::Numerics::IIncrementOperators<double>, System::Numerics::ILogarithmicFunctions<double>, System::Numerics::IMinMaxValue<double>, System::Numerics::IModulusOperators<double, double, double>, System::Numerics::IMultiplicativeIdentity<double, double>, System::Numerics::IMultiplyOperators<double, double, double>, System::Numerics::INumber<double>, System::Numerics::INumberBase<double>, System::Numerics::IPowerFunctions<double>, System::Numerics::IRootFunctions<double>, System::Numerics::ISignedNumber<double>, System::Numerics::ISubtractionOperators<double, double, double>, System::Numerics::ITrigonometricFunctions<double>, System::Numerics::IUnaryNegationOperators<double, double>, System::Numerics::IUnaryPlusOperators<double, double>
public value class double : IComparable<double>, IConvertible, IEquatable<double>, IParsable<double>, ISpanParsable<double>, IUtf8SpanFormattable, IUtf8SpanParsable<double>, System::Numerics::IAdditionOperators<double, double, double>, System::Numerics::IAdditiveIdentity<double, double>, System::Numerics::IBinaryFloatingPointIeee754<double>, System::Numerics::IBinaryNumber<double>, System::Numerics::IBitwiseOperators<double, double, double>, System::Numerics::IComparisonOperators<double, double, bool>, System::Numerics::IDecrementOperators<double>, System::Numerics::IDivisionOperators<double, double, double>, System::Numerics::IEqualityOperators<double, double, bool>, System::Numerics::IExponentialFunctions<double>, System::Numerics::IFloatingPoint<double>, System::Numerics::IFloatingPointConstants<double>, System::Numerics::IFloatingPointIeee754<double>, System::Numerics::IHyperbolicFunctions<double>, System::Numerics::IIncrementOperators<double>, System::Numerics::ILogarithmicFunctions<double>, System::Numerics::IMinMaxValue<double>, System::Numerics::IModulusOperators<double, double, double>, System::Numerics::IMultiplicativeIdentity<double, double>, System::Numerics::IMultiplyOperators<double, double, double>, System::Numerics::INumber<double>, System::Numerics::INumberBase<double>, System::Numerics::IPowerFunctions<double>, System::Numerics::IRootFunctions<double>, System::Numerics::ISignedNumber<double>, System::Numerics::ISubtractionOperators<double, double, double>, System::Numerics::ITrigonometricFunctions<double>, System::Numerics::IUnaryNegationOperators<double, double>, System::Numerics::IUnaryPlusOperators<double, double>
public value class double : IComparable, IConvertible, IFormattable
public value class double : IComparable, IComparable<double>, IEquatable<double>, IFormattable
public struct Double : IComparable, IComparable<double>, IConvertible, IEquatable<double>, IFormattable
public readonly struct Double : IComparable, IComparable<double>, IConvertible, IEquatable<double>, IFormattable
public readonly struct Double : IComparable, IComparable<double>, IConvertible, IEquatable<double>, ISpanFormattable
public readonly struct Double : IComparable<double>, IConvertible, IEquatable<double>, IParsable<double>, ISpanParsable<double>, System.Numerics.IAdditionOperators<double,double,double>, System.Numerics.IAdditiveIdentity<double,double>, System.Numerics.IBinaryFloatingPointIeee754<double>, System.Numerics.IBinaryNumber<double>, System.Numerics.IBitwiseOperators<double,double,double>, System.Numerics.IComparisonOperators<double,double,bool>, System.Numerics.IDecrementOperators<double>, System.Numerics.IDivisionOperators<double,double,double>, System.Numerics.IEqualityOperators<double,double,bool>, System.Numerics.IExponentialFunctions<double>, System.Numerics.IFloatingPoint<double>, System.Numerics.IFloatingPointConstants<double>, System.Numerics.IFloatingPointIeee754<double>, System.Numerics.IHyperbolicFunctions<double>, System.Numerics.IIncrementOperators<double>, System.Numerics.ILogarithmicFunctions<double>, System.Numerics.IMinMaxValue<double>, System.Numerics.IModulusOperators<double,double,double>, System.Numerics.IMultiplicativeIdentity<double,double>, System.Numerics.IMultiplyOperators<double,double,double>, System.Numerics.INumber<double>, System.Numerics.INumberBase<double>, System.Numerics.IPowerFunctions<double>, System.Numerics.IRootFunctions<double>, System.Numerics.ISignedNumber<double>, System.Numerics.ISubtractionOperators<double,double,double>, System.Numerics.ITrigonometricFunctions<double>, System.Numerics.IUnaryNegationOperators<double,double>, System.Numerics.IUnaryPlusOperators<double,double>
public readonly struct Double : IComparable<double>, IConvertible, IEquatable<double>, IParsable<double>, ISpanParsable<double>, IUtf8SpanFormattable, IUtf8SpanParsable<double>, System.Numerics.IAdditionOperators<double,double,double>, System.Numerics.IAdditiveIdentity<double,double>, System.Numerics.IBinaryFloatingPointIeee754<double>, System.Numerics.IBinaryNumber<double>, System.Numerics.IBitwiseOperators<double,double,double>, System.Numerics.IComparisonOperators<double,double,bool>, System.Numerics.IDecrementOperators<double>, System.Numerics.IDivisionOperators<double,double,double>, System.Numerics.IEqualityOperators<double,double,bool>, System.Numerics.IExponentialFunctions<double>, System.Numerics.IFloatingPoint<double>, System.Numerics.IFloatingPointConstants<double>, System.Numerics.IFloatingPointIeee754<double>, System.Numerics.IHyperbolicFunctions<double>, System.Numerics.IIncrementOperators<double>, System.Numerics.ILogarithmicFunctions<double>, System.Numerics.IMinMaxValue<double>, System.Numerics.IModulusOperators<double,double,double>, System.Numerics.IMultiplicativeIdentity<double,double>, System.Numerics.IMultiplyOperators<double,double,double>, System.Numerics.INumber<double>, System.Numerics.INumberBase<double>, System.Numerics.IPowerFunctions<double>, System.Numerics.IRootFunctions<double>, System.Numerics.ISignedNumber<double>, System.Numerics.ISubtractionOperators<double,double,double>, System.Numerics.ITrigonometricFunctions<double>, System.Numerics.IUnaryNegationOperators<double,double>, System.Numerics.IUnaryPlusOperators<double,double>
[System.Serializable]
public struct Double : IComparable, IConvertible, IFormattable
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public struct Double : IComparable, IComparable<double>, IConvertible, IEquatable<double>, IFormattable
public struct Double : IComparable, IComparable<double>, IEquatable<double>, IFormattable
type double = struct
    interface IConvertible
    interface IFormattable
type double = struct
    interface IConvertible
    interface ISpanFormattable
    interface IFormattable
type double = struct
    interface IConvertible
    interface IFormattable
    interface IParsable<double>
    interface ISpanFormattable
    interface ISpanParsable<double>
    interface IAdditionOperators<double, double, double>
    interface IAdditiveIdentity<double, double>
    interface IBinaryFloatingPointIeee754<double>
    interface IBinaryNumber<double>
    interface IBitwiseOperators<double, double, double>
    interface IComparisonOperators<double, double, bool>
    interface IEqualityOperators<double, double, bool>
    interface IDecrementOperators<double>
    interface IDivisionOperators<double, double, double>
    interface IIncrementOperators<double>
    interface IModulusOperators<double, double, double>
    interface IMultiplicativeIdentity<double, double>
    interface IMultiplyOperators<double, double, double>
    interface INumber<double>
    interface INumberBase<double>
    interface ISubtractionOperators<double, double, double>
    interface IUnaryNegationOperators<double, double>
    interface IUnaryPlusOperators<double, double>
    interface IExponentialFunctions<double>
    interface IFloatingPointConstants<double>
    interface IFloatingPoint<double>
    interface ISignedNumber<double>
    interface IFloatingPointIeee754<double>
    interface IHyperbolicFunctions<double>
    interface ILogarithmicFunctions<double>
    interface IPowerFunctions<double>
    interface IRootFunctions<double>
    interface ITrigonometricFunctions<double>
    interface IMinMaxValue<double>
type double = struct
    interface IConvertible
    interface IFormattable
    interface IParsable<double>
    interface ISpanFormattable
    interface ISpanParsable<double>
    interface IAdditionOperators<double, double, double>
    interface IAdditiveIdentity<double, double>
    interface IBinaryFloatingPointIeee754<double>
    interface IBinaryNumber<double>
    interface IBitwiseOperators<double, double, double>
    interface IComparisonOperators<double, double, bool>
    interface IEqualityOperators<double, double, bool>
    interface IDecrementOperators<double>
    interface IDivisionOperators<double, double, double>
    interface IIncrementOperators<double>
    interface IModulusOperators<double, double, double>
    interface IMultiplicativeIdentity<double, double>
    interface IMultiplyOperators<double, double, double>
    interface INumber<double>
    interface INumberBase<double>
    interface ISubtractionOperators<double, double, double>
    interface IUnaryNegationOperators<double, double>
    interface IUnaryPlusOperators<double, double>
    interface IUtf8SpanParsable<double>
    interface IExponentialFunctions<double>
    interface IFloatingPointConstants<double>
    interface IFloatingPoint<double>
    interface ISignedNumber<double>
    interface IFloatingPointIeee754<double>
    interface IHyperbolicFunctions<double>
    interface ILogarithmicFunctions<double>
    interface IPowerFunctions<double>
    interface IRootFunctions<double>
    interface ITrigonometricFunctions<double>
    interface IMinMaxValue<double>
    interface IUtf8SpanFormattable
[<System.Serializable>]
type double = struct
    interface IFormattable
    interface IConvertible
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type double = struct
    interface IFormattable
    interface IConvertible
type double = struct
    interface IFormattable
Public Structure Double
Implements IComparable, IComparable(Of Double), IConvertible, IEquatable(Of Double), IFormattable
Public Structure Double
Implements IComparable, IComparable(Of Double), IConvertible, IEquatable(Of Double), ISpanFormattable
Public Structure Double
Implements IAdditionOperators(Of Double, Double, Double), IAdditiveIdentity(Of Double, Double), IBinaryFloatingPointIeee754(Of Double), IBinaryNumber(Of Double), IBitwiseOperators(Of Double, Double, Double), IComparable(Of Double), IComparisonOperators(Of Double, Double, Boolean), IConvertible, IDecrementOperators(Of Double), IDivisionOperators(Of Double, Double, Double), IEqualityOperators(Of Double, Double, Boolean), IEquatable(Of Double), IExponentialFunctions(Of Double), IFloatingPoint(Of Double), IFloatingPointConstants(Of Double), IFloatingPointIeee754(Of Double), IHyperbolicFunctions(Of Double), IIncrementOperators(Of Double), ILogarithmicFunctions(Of Double), IMinMaxValue(Of Double), IModulusOperators(Of Double, Double, Double), IMultiplicativeIdentity(Of Double, Double), IMultiplyOperators(Of Double, Double, Double), INumber(Of Double), INumberBase(Of Double), IParsable(Of Double), IPowerFunctions(Of Double), IRootFunctions(Of Double), ISignedNumber(Of Double), ISpanParsable(Of Double), ISubtractionOperators(Of Double, Double, Double), ITrigonometricFunctions(Of Double), IUnaryNegationOperators(Of Double, Double), IUnaryPlusOperators(Of Double, Double)
Public Structure Double
Implements IAdditionOperators(Of Double, Double, Double), IAdditiveIdentity(Of Double, Double), IBinaryFloatingPointIeee754(Of Double), IBinaryNumber(Of Double), IBitwiseOperators(Of Double, Double, Double), IComparable(Of Double), IComparisonOperators(Of Double, Double, Boolean), IConvertible, IDecrementOperators(Of Double), IDivisionOperators(Of Double, Double, Double), IEqualityOperators(Of Double, Double, Boolean), IEquatable(Of Double), IExponentialFunctions(Of Double), IFloatingPoint(Of Double), IFloatingPointConstants(Of Double), IFloatingPointIeee754(Of Double), IHyperbolicFunctions(Of Double), IIncrementOperators(Of Double), ILogarithmicFunctions(Of Double), IMinMaxValue(Of Double), IModulusOperators(Of Double, Double, Double), IMultiplicativeIdentity(Of Double, Double), IMultiplyOperators(Of Double, Double, Double), INumber(Of Double), INumberBase(Of Double), IParsable(Of Double), IPowerFunctions(Of Double), IRootFunctions(Of Double), ISignedNumber(Of Double), ISpanParsable(Of Double), ISubtractionOperators(Of Double, Double, Double), ITrigonometricFunctions(Of Double), IUnaryNegationOperators(Of Double, Double), IUnaryPlusOperators(Of Double, Double), IUtf8SpanFormattable, IUtf8SpanParsable(Of Double)
Public Structure Double
Implements IComparable, IConvertible, IFormattable
Public Structure Double
Implements IComparable, IComparable(Of Double), IEquatable(Of Double), IFormattable
繼承
Double
屬性
實作
IComparable IComparable<Double> IConvertible IEquatable<Double> IFormattable ISpanFormattable IComparable<TSelf> IEquatable<TSelf> IParsable<Double> IParsable<TSelf> ISpanParsable<Double> ISpanParsable<TSelf> IAdditionOperators<Double,Double,Double> IAdditionOperators<TSelf,TSelf,TSelf> IAdditiveIdentity<Double,Double> IAdditiveIdentity<TSelf,TSelf> IBinaryFloatingPointIeee754<Double> IBinaryNumber<Double> IBinaryNumber<TSelf> IBitwiseOperators<Double,Double,Double> IBitwiseOperators<TSelf,TSelf,TSelf> IComparisonOperators<Double,Double,Boolean> IComparisonOperators<TSelf,TSelf,Boolean> IDecrementOperators<Double> IDecrementOperators<TSelf> IDivisionOperators<Double,Double,Double> IDivisionOperators<TSelf,TSelf,TSelf> IEqualityOperators<Double,Double,Boolean> IEqualityOperators<TSelf,TOther,TResult> IEqualityOperators<TSelf,TSelf,Boolean> IExponentialFunctions<Double> IExponentialFunctions<TSelf> IFloatingPoint<Double> IFloatingPoint<TSelf> IFloatingPointConstants<Double> IFloatingPointConstants<TSelf> IFloatingPointIeee754<Double> IFloatingPointIeee754<TSelf> IHyperbolicFunctions<Double> IHyperbolicFunctions<TSelf> IIncrementOperators<Double> IIncrementOperators<TSelf> ILogarithmicFunctions<Double> ILogarithmicFunctions<TSelf> IMinMaxValue<Double> IModulusOperators<Double,Double,Double> IModulusOperators<TSelf,TSelf,TSelf> IMultiplicativeIdentity<Double,Double> IMultiplicativeIdentity<TSelf,TSelf> IMultiplyOperators<Double,Double,Double> IMultiplyOperators<TSelf,TSelf,TSelf> INumber<Double> INumber<TSelf> INumberBase<Double> INumberBase<TSelf> IPowerFunctions<Double> IPowerFunctions<TSelf> IRootFunctions<Double> IRootFunctions<TSelf> ISignedNumber<Double> ISignedNumber<TSelf> ISubtractionOperators<Double,Double,Double> ISubtractionOperators<TSelf,TSelf,TSelf> ITrigonometricFunctions<Double> ITrigonometricFunctions<TSelf> IUnaryNegationOperators<Double,Double> IUnaryNegationOperators<TSelf,TSelf> IUnaryPlusOperators<Double,Double> IUnaryPlusOperators<TSelf,TSelf> IUtf8SpanFormattable IUtf8SpanParsable<Double> IUtf8SpanParsable<TSelf>

範例

下列程式碼範例說明 如何使用 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;
        }
    }
}
// The Temperature class stores the temperature as a Double
// and delegates most of the functionality to the Double
// implementation.
type Temperature() =
    member val Value = 0. with get, set

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

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

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

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

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

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

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

            Return m_value.CompareTo(temp.m_value)
        End If

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

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

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

        Return m_value.ToString(format, provider)
    End Function

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

        If s.TrimEnd(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.79769313486232e308,以及正數或負零、、 PositiveInfinityNegativeInfinity 和 不是數位 (NaN) 。 其目的在於表示極大型 (的值,例如行星之間的距離或) 或極小的 (,例如) ) 的分子品質,而且通常是不精確的 (,例如從地球到另一個太陽能系統的距離) 。 此 Double 類型符合二進位浮點算術的 IEC 60559:1989 (IEEE 754) 標準。

本主題包含下列章節:

Floating-Point 標記法和精確度

Double資料類型會以 64 位二進位格式儲存雙精確度浮點值,如下表所示:

部分 Bits
Significand 或 mantissa 0-51
指數 52-62
符號 (0 = 正數,1 = 負) 63

就如同小數分數無法精確地表示某些小數值 (,例如 1/3 或 Math.PI) ,二進位分數無法代表某些小數值。 例如,以十進位分數以 .1 精確表示的 1/10 是以 .001100110011 表示為二進位分數,而模式 「0011」 會重複到無限大。 在此情況下,浮點值會提供其所代表數位的不精確標記法。 在原始浮點值上執行其他數學運算通常會增加其缺乏精確度。 例如,如果我們比較將 .1 乘以 10 的結果,並將 .1 加到 .1 九次,我們會看到加法,因為它涉及 8 個以上的作業,所以會產生較不精確的結果。 請注意,只有在我們使用 「R」標準數值格式字串來顯示這兩 Double 個值時,才會明顯顯示此差異,必要時會顯示類型支援 Double 的所有 17 位數有效位數。

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
let value = 0.1
let result1 = value * 10.
let mutable result2 = 0.
for i = 1 to 10 do
    result2 <- result2 + value

printfn $".1 * 10:           {result1:R}"
printfn $".1 Added 10 times: {result2:R}"
// The example displays the following output:
//       .1 * 10:           1
//       .1 Added 10 times: 0.99999999999999989
Module 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

由於某些數位無法完全表示為小數二進位值,因此浮點數只能近似實數。

所有浮點數也有有限的有效位數,這也決定浮點值近似實數的精確度。 Double值最多可有 15 個小數位數的有效位數,雖然內部會維護最多 17 位數。 這表示某些浮點運算可能缺少變更浮點值的精確度。 下列範例提供說明。 它會定義非常大的浮點值,然後將 的乘 Double.Epsilon 積和一個四進階加入其中。 不過,產品太小而無法修改原始浮點值。 其最小有效位數為千分之一,而產品中最有效位數為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
open System

let value = 123456789012.34567
let additional = Double.Epsilon * 1e15
printfn $"{value} + {additional} = {value + additional}"
// The example displays the following output:
//    123456789012.346 + 4.94065645841247E-309 = 123456789012.346
Module 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

浮點數的有限有效位數有數個結果:

  • 對特定有效位數相等的兩個浮點數,可能因為它們的最低有效位數不同,而不相等。 在下列範例中,一連串的數位會加在一起,而且其總計會與其預期的總計進行比較。 雖然這兩個值似乎相同,但是對 方法的 Equals 呼叫表示它們不是。

    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).
    
    let values = [ 10.0; 2.88; 2.88; 2.88; 9.0 ]
    let result = 27.64
    let total = List.sum values
    
    if total.Equals result then
        printfn "The sum of the values equals the total."
    else
        printfn $"The sum of the values ({total}) does not equal the total ({result})."
    // The example displays the following output:
    //      The sum of the values (36.64) does not equal the total (36.64).
    //
    // If the index items in the Console.WriteLine statement are changed to {0:R},
    // the example displays the following output:
    //       The sum of the values (27.639999999999997) does not equal the total (27.64).
    
    Module 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 個值的所有有效位數,則清楚表示這兩個值在加法作業期間遺失有效位數不相等。 在此情況下,您可以藉由呼叫 Math.Round(Double, Int32) 方法來將值四舍 Double 五入到所需的精確度,再執行比較,來解決此問題。

  • 如果使用十進位數,則使用浮點數的數學或比較運算可能不會產生相同的結果,因為二進位浮點數可能不等於小數。 上一個範例說明如何顯示將 .1 乘以 10 並加 .1 次的結果。

    當數值運算中具有小數值的精確度很重要時,您可以使用 Decimal 而非 Double 類型。 當數值運算中具有超出 或 UInt64 類型範圍 Int64 之整數值的精確度很重要時,請使用 BigInteger 類型。

  • 如果涉及浮點數,則值可能不會來回。 如果作業將原始浮點數轉換成另一個表單,反向運算會將轉換後的表單轉換為浮點數,而最終浮點數不等於原始浮點數,則值會說為來回。 因為轉換中遺失或變更一或多個最小有效位數,所以來回行程可能會失敗。 在下列範例中,三 Double 個值會轉換成字串,並儲存在檔案中。 不過,如輸出所示,即使值看起來相同,還原的值不等於原始值。

    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
    
    open System
    open System.IO
    
    let values = [ 2.2 / 1.01; 1. / 3.; Math.PI ]
    
    using (new StreamWriter(@".\Doubles.dat")) (fun sw ->
        for i = 0 to values.Length - 1 do
            sw.Write(string values[i])
            if i <> values.Length - 1 then
                sw.Write "|")
    
    using (new StreamReader(@".\Doubles.dat")) (fun sr ->
        let temp = sr.ReadToEnd()
        let tempStrings = temp.Split '|'
    
        let restoredValues =
            [ for i = 0 to tempStrings.Length - 1 do
                  Double.Parse tempStrings[i] ]
    
        for i = 0 to values.Length - 1 do
            printfn $"""{values[i]} {if values[ i ].Equals restoredValues[i] then "=" else "<>"} {restoredValues[i]}""")
    
    // The example displays the following output:
    //       2.17821782178218 <> 2.17821782178218
    //       0.333333333333333 <> 0.333333333333333
    //       3.14159265358979 <> 3.14159265358979
    
    Imports System.IO
    
    Module 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 ,如下列範例所示。

    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
    
    open System
    open System.IO
    
    let values = [ 2.2 / 1.01; 1. / 3.; Math.PI ]
    
    using (new StreamWriter(@".\Doubles.dat")) (fun sw -> 
        for i = 0 to values.Length - 1 do
            sw.Write $"""{values[i]:G17}{if i < values.Length - 1 then "|" else ""}""")
    
    using (new StreamReader(@".\Doubles.dat")) (fun sr ->
        let temp = sr.ReadToEnd()
        let tempStrings = temp.Split '|'
        
        let restoredValues = 
          [ for i = 0 to tempStrings.Length - 1 do
                Double.Parse tempStrings[i] ]
    
        for i = 0 to values.Length - 1 do
            printfn $"""{restoredValues[i]} {if values[i].Equals restoredValues[i] then "=" else "<>"} {values[i]}""")
    
    // 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」 格式規範無法成功往返原始值。 若要確保 Double 值成功來回,請使用 「G17」 格式規範。

  • Single 值的有效位數小於 Double 值。 Single轉換成看似相等 Double 的值通常不等於值, Double 因為精確度的差異。 在下列範例中,相同的除法運算結果會指派給 DoubleSingle 值。 將 Single 值轉換成 Double 之後,兩個值的比較會顯示它們不相等。

    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
    
    open System
    
    let value1 = 1. / 3.
    let sValue2 = 1f /3f
    
    let value2 = double sValue2
    printfn $"{value1:R} = {value2:R}: {value1.Equals value2}"
    // The example displays the following output:
    //        0.33333333333333331 = 0.3333333432674408: False
    
    Module 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
    

    若要避免這個問題,請使用 DoubleSingle 取代資料類型,或使用 Round 方法,讓這兩個值具有相同的精確度。

此外,具有值的算術和指派運算 Double 結果可能會因型別的精確度 Double 遺失而因平臺而略有不同。 例如,指派常 Double 值的結果可能與 32 位和 64 位版本的.NET Framework不同。 下列範例說明當常值 -4.42330604244772E-305 和值為 -4.42330604244772E-305 Double 的變數時,這項差異。 請注意,在此情況下,方法的結果 Parse(String) 不會因為精確度遺失而受到影響。

double value = -4.42330604244772E-305;

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

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

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

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

測試是否相等

若要視為相等,兩 Double 個值必須代表相同的值。 不過,由於值之間的精確度差異,或因為一或兩個值遺失有效位數,因此預期相同的浮點值通常因為其最小有效位數的差異而不相等。 因此,呼叫 Equals 方法以判斷兩個值是否相等,或呼叫 CompareTo 方法來判斷兩 Double 個值之間的關聯性,通常會產生非預期的結果。 這在下列範例中很明顯,其中兩個明顯相等 Double 的值會變成不相等,因為第一個有 15 位數的有效位數,而第二個數字有 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
open System

let value1 = 0.333333333333333
let value2 = 1. / 3.
printfn $"{value1:R} = {value2:R}: {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

遵循不同程式碼路徑且以不同方式操作的匯出值,通常證明不相等。 在下列範例中,一個 Double 值是平方,然後計算平方根來還原原始值。 第二 Double 個乘以 3.51,並在結果平方根除以 3.51 之前平方以還原原始值。 雖然這兩個值似乎相同,但是對 方法的 Equals(Double) 呼叫表示它們不相等。 使用 「R」 標準格式字串傳回結果字串,其中顯示每個 Double 值的所有有效位數,顯示第二個值是 .0000000000001小於第一個值。

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
open System

let value1 = 
    Math.Pow(100.10142, 2)
    |> sqrt

let value2 = 
    let v = pown (value1 * 3.51) 2
    (Math.Sqrt v) / 3.51

printfn $"{value1} = {value2}: {value1.Equals value2}\n"
printfn $"{value1:R} = {value2:R}"
// 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 方法:

  • Math.Round呼叫 方法,以確保這兩個值具有相同的精確度。 下列範例會修改先前的範例,以使用此方法,讓兩個小數值相等。

    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
    
    open System
    
    let v1 = 0.333333333333333
    let v2 = 1. / 3.
    let precision = 7
    let value1 = Math.Round(v1, precision)
    let value2 = Math.Round(v2, precision)
    printfn $"{value1:R} = {value2:R}: {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
    

    精確度的問題仍適用于中間點值的四捨五入。 如需詳細資訊,請參閱 Math.Round(Double, Int32, MidpointRounding) 方法。

  • 測試近似相等,而不是相等。 這需要您定義兩個值可以相異但仍然相等的絕對數量,或定義較小的值可以從較大的值除以相等的相對數量。

    警告

    Double.Epsilon 在測試是否相等時,有時會當做兩 Double 個值之間距離的絕對量值。 不過, Double.Epsilon 測量可以加入或減去 Double 其值為零的 最小可能值。 對於大部分的正值和負 Double 值,的值 Double.Epsilon 太小而無法偵測。 因此,除了零的值以外,我們不建議在測試中使用是否相等。

    下列範例會使用後者方法來定義方法,以測試兩個 IsApproximatelyEqual 值之間的相對差異。 它也會對比呼叫 IsApproximatelyEqual 方法和 Equals(Double) 方法的結果。

    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
    
    open System
    
    let isApproximatelyEqual (value1: double) (value2: double) (epsilon: double) =
        // If they are equal anyway, just return True.
        if value1.Equals value2 then 
            true
        else
            // Handle NaN, Infinity.
            if Double.IsInfinity value1 || Double.IsNaN value1 then 
                value1.Equals value2
            elif Double.IsInfinity value2 || Double.IsNaN value2 then
                value1.Equals value2
            else
                // Handle zero to avoid division by zero
                let divisor = max value1 value2
                let divisor = 
                    if divisor.Equals 0 then
                        min value1 value2
                    else 
                        divisor
                abs ((value1 - value2) / divisor) <= epsilon
    
    let one1 = 0.1 * 10.
    let mutable one2 = 0.
    for _ = 1 to 10 do
        one2 <- one2 + 0.1
    
    printfn $"{one1:R} = {one2:R}: {one1.Equals one2}"
    printfn $"{one1:R} is approximately equal to {one2:R}: {isApproximatelyEqual one1 one2 0.000000001}"
    
    // 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 值和例外狀況

不同于整數型別的作業,若發生溢位或不合法的作業,例如除以零,則具有浮點值的作業不會擲回例外狀況。 相反地,在例外情況下,浮點運算的結果為零、正無限大、負無限大,或非數位 (NaN) :

  • 如果浮點運算的結果對目的地格式而言太小,則結果為零。 當兩個非常小的數位相乘時,就會發生這種情況,如下列範例所示。

    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
    
    let value1 = 1.1632875981534209e-225
    let value2 = 9.1642346778e-175
    let result = value1 * value2
    printfn $"{value1} * {value2} = {result}"
    printfn $"{result} = 0: {result.Equals 0.0}"
    // The example displays the following output:
    //       1.16328759815342E-225 * 9.1642346778E-175 = 0
    //       0 = 0: True
    
    Module 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
    
  • 如果浮點運算的結果大小超過目的格式的範圍,則作業的結果會 PositiveInfinity 是 或 NegativeInfinity ,適用于結果的正負號。 溢位 Double.MaxValue 作業的結果為 PositiveInfinity ,而溢位 Double.MinValue 作業的結果為 NegativeInfinity ,如下列範例所示。

    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
    
    open System
    
    let value1 = 4.565e153
    let value2 = 6.9375e172
    let result = value1 * value2
    printfn $"PositiveInfinity: {Double.IsPositiveInfinity result}"
    printfn $"NegativeInfinity: {Double.IsNegativeInfinity result}\n"
    
    let value3 = - value1
    let result2 = value2 * value3
    printfn $"PositiveInfinity: {Double.IsPositiveInfinity result2}"
    printfn $"NegativeInfinity: {Double.IsNegativeInfinity result2}"
    
    // The example displays the following output:
    //       PositiveInfinity: True
    //       NegativeInfinity: False
    //
    //       PositiveInfinity: False
    //       NegativeInfinity: True
    
    Module 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 零除以負數除數的結果。

  • 如果浮點運算無效,作業的結果為 NaN 。 例如, NaN 下列作業的結果:

  • 任何具有無效輸入的浮點運算。 例如,使用負值呼叫 Math.Sqrt 方法會 NaN 傳回 ,如同使用大於一或小於負值的值呼叫 Math.Acos 方法一樣。

  • 具有其值為 Double.NaN 之引數的任何作業。

類型轉換和 Double 結構

結構 Double 不會定義任何明確或隱含轉換運算子,而是由編譯器實作轉換。

將任何基本數值型 Double 別的值轉換成 是擴輾轉換,因此不需要明確轉換運算子或呼叫轉換方法,除非編譯器明確要求轉換方法。 例如,C# 編譯器需要轉換運算子,才能從 Decimal 轉換成 Double ,而 Visual Basic 編譯器則不需要。 下列範例會將其他基本數數值型別的最小值或最大值轉換為 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)
open System

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

for value in values do
    let dblValue = value :?> double
    printfn $"{value} ({value.GetType().Name}) --> {dblValue:R} ({dblValue.GetType().Name})"
// The example displays the following output:
//    0 (Byte) --> 0 (Double)
//    255 (Byte) --> 255 (Double)
//    -79228162514264337593543950335 (Decimal) --> -7.9228162514264338E+28 (Double)
//    79228162514264337593543950335 (Decimal) --> 7.9228162514264338E+28 (Double)
//    -32768 (Int16) --> -32768 (Double)
//    32767 (Int16) --> 32767 (Double)
//    -2147483648 (Int32) --> -2147483648 (Double)
//    2147483647 (Int32) --> 2147483647 (Double)
//    -9223372036854775808 (Int64) --> -9.2233720368547758E+18 (Double)
//    9223372036854775807 (Int64) --> 9.2233720368547758E+18 (Double)
//    -128 (SByte) --> -128 (Double)
//    127 (SByte) --> 127 (Double)
//    -3.402823E+38 (Single) --> -3.4028234663852886E+38 (Double)
//    3.402823E+38 (Single) --> 3.4028234663852886E+38 (Double)
//    0 (UInt16) --> 0 (Double)
//    65535 (UInt16) --> 65535 (Double)
//    0 (UInt32) --> 0 (Double)
//    4294967295 (UInt32) --> 4294967295 (Double)
//    0 (UInt64) --> 0 (Double)
//    18446744073709551615 (UInt64) --> 1.8446744073709552E+19 (Double)
Module 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)

此外, Single 、、 和 Single.NegativeInfinity 的值 Single.PositiveInfinitySingle.NaN 會分別轉換成 Double.NaNDouble.PositiveInfinityDouble.NegativeInfinity

請注意,將某些數值型 Double 別的值轉換成值,可能會牽涉到精確度遺失。 如範例所示,將 、 Int64UInt64 值轉換成 DecimalDouble 時,可能會遺失有效位數。

將值轉換成 Double 任何其他基本數值資料類型的值是縮小轉換,而且需要 C#) 中的轉換運算子 (、Visual Basic) 中的轉換方法 (,或呼叫 Convert 方法。 超出目標資料類型範圍的值,這些資料類型是由目標型別的 MinValueMaxValue 屬性所定義,其行為如下表所示。

目標類型 結果
任何整數類型 OverflowException如果轉換發生在已檢查的內容中,則為例外狀況。

如果在未核取的內容中發生轉換, (C#) 中的預設值,轉換作業就會成功,但值溢位。
Decimal OverflowException 例外狀況。
Single Single.NegativeInfinity 為負值。

Single.PositiveInfinity 為正值。

此外, Double.NaNDouble.PositiveInfinityDouble.NegativeInfinity 會擲回 OverflowException ,以便轉換成已檢查內容中的整數,但這些值會在未核取的內容中轉換成整數時溢位。 若要轉換成 Decimal ,它們一律會擲回 OverflowException 。 若要轉換成 Single ,它們分別轉換成 Single.NaNSingle.PositiveInfinitySingle.NegativeInfinity

請注意,精確度遺失可能會導致將值轉換成另一個 Double 數數值型別。 在轉換成任何整數型別的情況下,如範例所示,當值如 Visual Basic) 四捨五入 (或截斷 (為 C#) 時 Double ,小陣列件會遺失。 針對 和 DecimalSingle 值的轉換, Double 值在目標資料類型中可能沒有精確的標記法。

下列範例會將一些 Double 值轉換成數個其他數數值型別。 轉換發生在 Visual Basic 中檢查的內容中, (預設) 、C# (,因為 checked 關鍵字) ,而 F# (是因為 Checked 模組) 。 範例的輸出會顯示在已核取未核取內容中轉換的結果。 您可以在 Visual Basic 中未核取的內容中執行轉換,方法是使用 /removeintchecks+ 編譯器參數進行編譯、在 C# 中透過批註化 checked 語句,以及在 F# 中將 語句加上批註 open Checked

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)
open System
open Checked

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

for value in values do
    try
        let lValue = int64 value
        printfn $"{value} ({value.GetType().Name}) --> {lValue} (0x{lValue:X16}) ({lValue.GetType().Name})"
    with :? OverflowException ->
        printfn $"Unable to convert {value} to Int64."
    try
        let ulValue = uint64 value
        printfn $"{value} ({value.GetType().Name}) --> {ulValue} (0x{ulValue:X16}) ({ulValue.GetType().Name})"
    with :? OverflowException ->
        printfn $"Unable to convert {value} to UInt64."
    try
        let dValue = decimal value
        printfn $"{value} ({value.GetType().Name}) --> {dValue} ({dValue.GetType().Name})"
    with :? OverflowException ->
        printfn $"Unable to convert {value} to Decimal."
    try
        let sValue = float32 value
        printfn $"{value} ({value.GetType().Name}) --> {sValue} ({sValue.GetType().Name})"
    with :? OverflowException ->
        printfn $"Unable to convert {value} to Single."
    printfn ""
// The example displays the following output for conversions performed
// in a checked context:
//       Unable to convert -1.79769313486232E+308 to Int64.
//       Unable to convert -1.79769313486232E+308 to UInt64.
//       Unable to convert -1.79769313486232E+308 to Decimal.
//       -1.79769313486232E+308 (Double) --> -Infinity (Single)
//
//       -67890.1234 (Double) --> -67890 (0xFFFFFFFFFFFEF6CE) (Int64)
//       Unable to convert -67890.1234 to UInt64.
//       -67890.1234 (Double) --> -67890.1234 (Decimal)
//       -67890.1234 (Double) --> -67890.13 (Single)
//
//       -12345.6789 (Double) --> -12345 (0xFFFFFFFFFFFFCFC7) (Int64)
//       Unable to convert -12345.6789 to UInt64.
//       -12345.6789 (Double) --> -12345.6789 (Decimal)
//       -12345.6789 (Double) --> -12345.68 (Single)
//
//       12345.6789 (Double) --> 12345 (0x0000000000003039) (Int64)
//       12345.6789 (Double) --> 12345 (0x0000000000003039) (UInt64)
//       12345.6789 (Double) --> 12345.6789 (Decimal)
//       12345.6789 (Double) --> 12345.68 (Single)
//
//       67890.1234 (Double) --> 67890 (0x0000000000010932) (Int64)
//       67890.1234 (Double) --> 67890 (0x0000000000010932) (UInt64)
//       67890.1234 (Double) --> 67890.1234 (Decimal)
//       67890.1234 (Double) --> 67890.13 (Single)
//
//       Unable to convert 1.79769313486232E+308 to Int64.
//       Unable to convert 1.79769313486232E+308 to UInt64.
//       Unable to convert 1.79769313486232E+308 to Decimal.
//       1.79769313486232E+308 (Double) --> Infinity (Single)
//
//       Unable to convert NaN to Int64.
//       Unable to convert NaN to UInt64.
//       Unable to convert NaN to Decimal.
//       NaN (Double) --> NaN (Single)
//
//       Unable to convert Infinity to Int64.
//       Unable to convert Infinity to UInt64.
//       Unable to convert Infinity to Decimal.
//       Infinity (Double) --> Infinity (Single)
//
//       Unable to convert -Infinity to Int64.
//       Unable to convert -Infinity to UInt64.
//       Unable to convert -Infinity to Decimal.
//       -Infinity (Double) --> -Infinity (Single)
// The example displays the following output for conversions performed
// in an unchecked context:
//       -1.79769313486232E+308 (Double) --> -9223372036854775808 (0x8000000000000000) (Int64)
//       -1.79769313486232E+308 (Double) --> 9223372036854775808 (0x8000000000000000) (UInt64)
//       Unable to convert -1.79769313486232E+308 to Decimal.
//       -1.79769313486232E+308 (Double) --> -Infinity (Single)
//
//       -67890.1234 (Double) --> -67890 (0xFFFFFFFFFFFEF6CE) (Int64)
//       -67890.1234 (Double) --> 18446744073709483726 (0xFFFFFFFFFFFEF6CE) (UInt64)
//       -67890.1234 (Double) --> -67890.1234 (Decimal)
//       -67890.1234 (Double) --> -67890.13 (Single)
//
//       -12345.6789 (Double) --> -12345 (0xFFFFFFFFFFFFCFC7) (Int64)
//       -12345.6789 (Double) --> 18446744073709539271 (0xFFFFFFFFFFFFCFC7) (UInt64)
//       -12345.6789 (Double) --> -12345.6789 (Decimal)
//       -12345.6789 (Double) --> -12345.68 (Single)
//
//       12345.6789 (Double) --> 12345 (0x0000000000003039) (Int64)
//       12345.6789 (Double) --> 12345 (0x0000000000003039) (UInt64)
//       12345.6789 (Double) --> 12345.6789 (Decimal)
//       12345.6789 (Double) --> 12345.68 (Single)
//
//       67890.1234 (Double) --> 67890 (0x0000000000010932) (Int64)
//       67890.1234 (Double) --> 67890 (0x0000000000010932) (UInt64)
//       67890.1234 (Double) --> 67890.1234 (Decimal)
//       67890.1234 (Double) --> 67890.13 (Single)
//
//       1.79769313486232E+308 (Double) --> -9223372036854775808 (0x8000000000000000) (Int64)
//       1.79769313486232E+308 (Double) --> 0 (0x0000000000000000) (UInt64)
//       Unable to convert 1.79769313486232E+308 to Decimal.
//       1.79769313486232E+308 (Double) --> Infinity (Single)
//
//       NaN (Double) --> -9223372036854775808 (0x8000000000000000) (Int64)
//       NaN (Double) --> 0 (0x0000000000000000) (UInt64)
//       Unable to convert NaN to Decimal.
//       NaN (Double) --> NaN (Single)
//
//       Infinity (Double) --> -9223372036854775808 (0x8000000000000000) (Int64)
//       Infinity (Double) --> 0 (0x0000000000000000) (UInt64)
//       Unable to convert Infinity to Decimal.
//       Infinity (Double) --> Infinity (Single)
//
//       -Infinity (Double) --> -9223372036854775808 (0x8000000000000000) (Int64)
//       -Infinity (Double) --> 9223372036854775808 (0x8000000000000000) (UInt64)
//       Unable to convert -Infinity to Decimal.
//       -Infinity (Double) --> -Infinity (Single)
Module 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類型轉換資料表中的類型轉換

Floating-Point 功能

結構和 Double 相關類型提供方法,以在下欄區域中執行作業:

  • 值的比較。 您可以呼叫 Equals 方法來判斷兩 Double 個值是否相等,或 CompareTo 呼叫 方法來判斷兩個值之間的關聯性。

    結構 Double 也支援一組完整的比較運算子。 例如,您可以測試是否相等或不相等,或判斷某個值是否大於或等於另一個值。 如果其中一個運算元是 以外的 Double 數數值型別,則會先轉換成 Double ,再執行比較。

    警告

    由於精確度的差異,您預期相等的兩 Double 個值可能會不相等,這會影響比較的結果。 如需比較兩 Double 個值的詳細資訊,請參閱一節。

    您也可以呼叫 IsNaNIsInfinityIsPositiveInfinityIsNegativeInfinity 方法來測試這些特殊值。

  • 數學運算。 常見的算數運算,例如加法、減法、乘法和除法,都是由語言編譯器和 Common Intermediate Language (CIL) 指令實作,而不是由 Double 方法實作。 如果數學運算中的其中一個運算元是 以外的 Double 數數值型別,則會在執行 Double 作業之前轉換為 。 作業的結果也是 Double 值。

    您可以在 Visual Basic 中呼叫 static (Shared) 方法, System.Math 以執行其他數學運算。 其中包含常用於算術 (的其他方法,例如 Math.AbsMath.SignMath.Sqrt) 、幾何 (,例如 Math.CosMath.Sin) ,以及微數 (,例如 Math.Log) 。

    您也可以操作 值中的 Double 個別位。 方法 BitConverter.DoubleToInt64Bits 會在 Double 64 位整數中保留值的位模式。 方法 BitConverter.GetBytes(Double) 會在位元組陣列中傳回其位模式。

  • 四捨五入。 四捨五入通常用來做為減少浮點表示和精確度問題所造成值間差異影響的技術。 您可以藉由呼叫 Math.Round 方法來四捨五入 Double 值。

  • 格式化。 您可以呼叫 方法或使用複合格式功能, ToString 將值轉換成 Double 其字串表示。 如需格式字串如何控制浮點值的字串表示的詳細資訊,請參閱 標準數值格式字串自訂數值格式字串 主題。

  • 剖析字串。 您可以藉由呼叫 ParseTryParse 方法,將浮點值的字串表示轉換為 Double 值。 如果剖析作業失敗,方法 Parse 會擲回例外狀況,而 方法會 TryParsefalse 回 。

  • 類型轉換。 結構 Double 會為 介面提供明確的介面實作 IConvertible ,可支援在任兩個標準.NET Framework資料類型之間進行轉換。 語言編譯器也支援將所有其他標準數數值型別的 Double 值隱含轉換成值。 將任何標準數值型 Double 別的值轉換成 是擴輾轉換,而且不需要轉型運算子或轉換方法的使用者。

    不過,和 Single 值的 Int64 轉換可能會牽涉到精確度遺失。 下表列出每種類型的有效位數差異:

    類型 最大有效位數 內部有效位數
    Double 15 17
    Int64 19 個小數位數 19 個小數位數
    Single 7 個小數位數 9 個小數位數

    有效位數的問題最常影響 Single 轉換成 Double 值的值。 在下列範例中,相同除法運算所產生的兩個值不相等,因為其中一個值是轉換成 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
    
    let value = 0.1
    let result1 = value * 10.
    let mutable result2 = 0.
    for i = 1 to 10 do
        result2 <- result2 + value
    
    printfn $".1 * 10:           {result1:R}"
    printfn $".1 Added 10 times: {result2:R}"
    // The example displays the following output:
    //       .1 * 10:           1
    //       .1 Added 10 times: 0.99999999999999989
    
    Module 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
    

欄位

E

表示常數所指定的自然對數基底,e.

Epsilon

代表大於零的最小正 Double 值。 這個欄位為常數。

MaxValue

表示 Double 最大的可能值。 這個欄位為常數。

MinValue

表示 Double 最小的可能值。 這個欄位為常數。

NaN

代表不是數字 (NaN) 的值。 這個欄位為常數。

NegativeInfinity

表示負無限大。 這個欄位為常數。

NegativeZero

表示負數零 (-0) 。

Pi

代表圓周率,由常數 π 指定。

PositiveInfinity

表示正無限大。 這個欄位為常數。

Tau

代表單一回合中的弧度數目,由常數 τ 指定。

方法

Abs(Double)

計算值的絕對值。

Acos(Double)

計算值的反余弦值。

Acosh(Double)

計算值的雙曲反余弦值。

AcosPi(Double)

計算值的反余弦值,並將結果除以 pi

Asin(Double)

計算值的反正弦值。

Asinh(Double)

計算值的雙曲反正弦值。

AsinPi(Double)

計算值的反正弦值,並將結果除以 pi

Atan(Double)

計算值的反正切值。

Atan2(Double, Double)

計算兩個值商的反正切值。

Atan2Pi(Double, Double)

計算兩個值商的反正切值,並將結果除以 pi

Atanh(Double)

計算值的雙曲反正切值。

AtanPi(Double)

計算值的反正切值,並將結果除以 pi。

BitDecrement(Double)

將值遞減為小於指定值的最小值。

BitIncrement(Double)

將值遞增為與指定值相比較的最小值。

Cbrt(Double)

計算值的 Cube 根目錄。

Ceiling(Double)

計算值的上限。

Clamp(Double, Double, Double)

將值限制為內含最小值和最大值。

CompareTo(Double)

比較這個執行個體與雙精確度的浮點數值,並且傳回一個整數,指出這個執行個體的值是小於、等於或大於特定的雙精確度浮點數值。

CompareTo(Object)

比較這個執行個體與特定物件,並且傳回一個整數,指出這個執行個體的值是小於、等於或大於特定物件的值。

CopySign(Double, Double)

將值的正負號複製到另一個值的正負號。

Cos(Double)

計算值的余弦值。

Cosh(Double)

計算值的雙曲余弦值。

CosPi(Double)

計算 已由 pi 多乘之值的余弦值。

CreateChecked<TOther>(TOther)

從值建立目前型別的實例,針對落在目前類型可表示範圍以外的任何值擲回溢位例外狀況。

CreateSaturating<TOther>(TOther)

從值建立目前型別的實例,使落在目前類型可表示範圍以外的任何值飽和。

CreateTruncating<TOther>(TOther)

從值建立目前型別的實例,截斷落在目前類型可表示範圍以外的任何值。

DegreesToRadians(Double)

將指定的值從度轉換為弧度。

Equals(Double)

傳回值,該值表示這個執行個體和指定的 Double 物件是否代表相同值。

Equals(Object)

傳回值,該值表示這個執行個體是否和指定的物件相等。

Exp(Double)

E計算會引發至指定電源。

Exp10(Double)

10計算會引發至指定電源。

Exp10M1(Double)

10計算會引發至指定的乘冪,並減去一個。

Exp2(Double)

2計算會引發至指定電源。

Exp2M1(Double)

2計算會引發至指定的乘冪,並減去一個。

ExpM1(Double)

E計算會引發至指定的乘冪,並減去一個。

Floor(Double)

計算值的底板。

FusedMultiplyAdd(Double, Double, Double)

計算三個值的融合乘法。

GetHashCode()

傳回這個執行個體的雜湊碼。

GetTypeCode()

傳回實值類型 TypeCodeDouble

Hypot(Double, Double)

計算假設有兩個值,代表右角三角形中較短側邊的長度。

Ieee754Remainder(Double, Double)

計算 IEEE 754 所指定兩個值的其餘部分。

ILogB(Double)

計算值的整數對數。

IsEvenInteger(Double)

判斷值是否代表偶數整數。

IsFinite(Double)

判斷指定的值是否為有限 (零、偏低或一般)。

IsInfinity(Double)

傳回值,指出指定的數字是否計算結果為負或正的無限大。

IsInteger(Double)

判斷值是否代表整數值。

IsNaN(Double)

傳回值,該值表示指定的值是否不是數字 (NaN)。

IsNegative(Double)

判斷指定的值是否為負數。

IsNegativeInfinity(Double)

傳回值,指出指定的數字是否計算結果為負的無限大。

IsNormal(Double)

判斷指定的值是否為正常。

IsOddInteger(Double)

判斷值是否代表奇數整數。

IsPositive(Double)

判斷值是否為正數。

IsPositiveInfinity(Double)

傳回值,指出指定數字是否計算結果為正的無限大。

IsPow2(Double)

判斷值是否為兩個的乘冪。

IsRealNumber(Double)

判斷值是否代表實數。

IsSubnormal(Double)

判斷指定的值是否為偏低。

Lerp(Double, Double, Double)

根據指定的權數,在兩個值之間執行線性插補。

Log(Double)

計算值的自然 (base-E 對數。

Log(Double, Double)

計算指定基底中值的對數。

Log10(Double)

計算值的 base-10 對數。

Log10P1(Double)

計算值的 base-10 對數加上一。

Log2(Double)

計算值的 log2。

Log2P1(Double)

計算值的基底 2 對數加上一。

LogP1(Double)

計算值加上一) 對數的自然 (base-E

Max(Double, Double)

比較兩個值與大於的計算。

MaxMagnitude(Double, Double)

比較兩個值與大於的計算。

MaxMagnitudeNumber(Double, Double)

比較兩個值與具有更大大小的計算,如果輸入為 NaN ,則會傳回另一個值。

MaxNumber(Double, Double)

比較兩個值與計算,如果輸入為 NaN ,則會傳回另一個值。

Min(Double, Double)

比較兩個值與比較較少的計算。

MinMagnitude(Double, Double)

比較兩個值與比較較少的計算。

MinMagnitudeNumber(Double, Double)

比較兩個值與計算,如果輸入為 NaN ,則其大小較小,並傳回其他值。

MinNumber(Double, Double)

比較兩個值與計算,如果輸入為 NaN ,則會傳回另一個值。

Parse(ReadOnlySpan<Byte>, IFormatProvider)

將 UTF-8 字元的範圍剖析為值。

Parse(ReadOnlySpan<Byte>, NumberStyles, IFormatProvider)

將 UTF-8 字元的範圍剖析為值。

Parse(ReadOnlySpan<Char>, IFormatProvider)

將字元範圍剖析為值。

Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider)

將包含數字字串表示 (使用指定樣式和特定文化特性格式) 的字元範圍轉換為其對等的雙精確度浮點數。

Parse(String)

將數字的字串表示轉換為其相等的雙精確度浮點數。

Parse(String, IFormatProvider)

將數字的字串表示 (使用指定的特定文化特性格式) 轉換為其相等的雙精確度浮點數。

Parse(String, NumberStyles)

將數字的字串表示 (使用指定樣式) 轉換為其相等的雙精確度浮點數。

Parse(String, NumberStyles, IFormatProvider)

使用指定樣式和特定文化特性格式,將數字的字串表示轉換為其相等的雙精確度浮點數。

Pow(Double, Double)

計算向指定之乘冪引發的值。

RadiansToDegrees(Double)

將指定的值從弧度轉換為度。

ReciprocalEstimate(Double)

計算值的相互值估計值。

ReciprocalSqrtEstimate(Double)

計算值之相互平方根的估計值。

RootN(Double, Int32)

計算值的第 n 個根目錄。

Round(Double)

使用預設四捨五入模式將值四捨五入為最接近的整數, (ToEven) 。

Round(Double, Int32)

使用預設四捨五入模式,將值四捨五入為指定的小數位數, (ToEven) 。

Round(Double, Int32, MidpointRounding)

使用預設四捨五入模式,將值四捨五入為指定的小數位數, (ToEven) 。

Round(Double, MidpointRounding)

使用指定的進位模式,將值四捨五入為最接近的整數。

ScaleB(Double, Int32)

計算值乘積,以及其基底弧度乘以指定的乘冪。

Sign(Double)

計算值的符號。

Sin(Double)

計算值的正弦值。

SinCos(Double)

計算值的正弦和余弦值。

SinCosPi(Double)

計算值的正弦和余弦值。

Sinh(Double)

計算值的雙曲正弦值。

SinPi(Double)

計算已乘以 pi 之值的正弦值。

Sqrt(Double)

計算值的平方根。

Tan(Double)

計算值的正切值。

Tanh(Double)

計算值的雙曲正切值。

TanPi(Double)

計算 已由 pi 複寫的值正切值。

ToString()

將這個執行個體的數值轉換為其相等字串表示。

ToString(IFormatProvider)

使用指定的特定文化特性格式資訊,將這個執行個體的數值轉換成它的相等字串表示。

ToString(String)

使用指定格式,將這個執行個體的數值轉換成它的相等字串表示。

ToString(String, IFormatProvider)

使用指定的格式和特定文化特性格式資訊,將這個執行個體的數值轉換成它的相等字串表示。

Truncate(Double)

截斷值。

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

嘗試將目前實例的值格式化為 UTF-8 到提供的位元組範圍。

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

嘗試將目前雙精確度浮點數執行個體的值格式化為所提供的字元範圍。

TryParse(ReadOnlySpan<Byte>, Double)

嘗試將包含數位字串表示的 UTF-8 字元範圍轉換為其對等雙精確度浮點數。

TryParse(ReadOnlySpan<Byte>, IFormatProvider, Double)

嘗試將 UTF-8 字元的範圍剖析為值。

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

嘗試將 UTF-8 字元的範圍剖析為值。

TryParse(ReadOnlySpan<Char>, Double)

將數字的範圍表示 (使用指定樣式和特定文化特性格式) 轉換為其對等的雙精確度浮點數。 傳回值,該值指出轉換成功或失敗。

TryParse(ReadOnlySpan<Char>, IFormatProvider, Double)

嘗試將字元範圍剖析為值。

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

將包含數字字串表示 (使用指定樣式和特定文化特性格式) 的字元範圍轉換為其對等的雙精確度浮點數。 傳回值,該值指出轉換成功或失敗。

TryParse(String, Double)

將數字的字串表示轉換為其相等的雙精確度浮點數。 傳回值,該值指出轉換成功或失敗。

TryParse(String, IFormatProvider, Double)

嘗試將字串剖析成值。

TryParse(String, NumberStyles, IFormatProvider, Double)

使用指定樣式和特定文化特性格式,將數字的字串表示轉換為其相等的雙精確度浮點數。 傳回值,該值指出轉換成功或失敗。

運算子

Equality(Double, Double)

傳回值,該值表示兩個指定的 Double 值是否相等。

GreaterThan(Double, Double)

傳回值,該值表示指定的 Double 值是否大於另一個指定的 Double 值。

GreaterThanOrEqual(Double, Double)

傳回值,該值表示指定的 Double 值是否大於或等於另一個指定的 Double 值。

Inequality(Double, Double)

傳回值,該值表示兩個指定的 Double 值是否不相等。

LessThan(Double, Double)

傳回值,該值表示指定的 Double 值是否小於另一個指定的 Double 值。

LessThanOrEqual(Double, Double)

傳回值,該值表示指定的 Double 值是否小於或等於另一個指定的 Double 值。

明確介面實作

IAdditionOperators<Double,Double,Double>.Addition(Double, Double)

將兩個值加在一起,以計算其總和。

IAdditiveIdentity<Double,Double>.AdditiveIdentity

取得目前類型的加法識別。

IBinaryNumber<Double>.AllBitsSet

取得二進位類型的實例,其中已設定所有位。

IBitwiseOperators<Double,Double,Double>.BitwiseAnd(Double, Double)

計算兩個值的位和 。

IBitwiseOperators<Double,Double,Double>.BitwiseOr(Double, Double)

計算兩個值的位或兩個值。

IBitwiseOperators<Double,Double,Double>.ExclusiveOr(Double, Double)

計算兩個值的獨佔或兩個值。

IBitwiseOperators<Double,Double,Double>.OnesComplement(Double)

計算指定值的 ones-補數標記法。

IComparable.CompareTo(Object)

將目前的執行個體與相同類型的另一個物件相比較,並傳回整數,這個整數表示目前的執行個體在排序次序中,位於另一個物件之前、之後或相同位置。

IConvertible.GetTypeCode()

傳回這個執行個體的 TypeCode

IConvertible.ToBoolean(IFormatProvider)

如需這個成員的說明,請參閱 ToBoolean(IFormatProvider)

IConvertible.ToByte(IFormatProvider)

如需這個成員的說明,請參閱 ToByte(IFormatProvider)

IConvertible.ToChar(IFormatProvider)

不支援此轉換。 嘗試使用這個方法會擲回 InvalidCastException

IConvertible.ToDateTime(IFormatProvider)

不支援此轉換。 嘗試使用這個方法會擲回 InvalidCastException

IConvertible.ToDecimal(IFormatProvider)

如需這個成員的說明,請參閱 ToDecimal(IFormatProvider)

IConvertible.ToDouble(IFormatProvider)

如需這個成員的說明,請參閱 ToDouble(IFormatProvider)

IConvertible.ToInt16(IFormatProvider)

如需這個成員的說明,請參閱 ToInt16(IFormatProvider)

IConvertible.ToInt32(IFormatProvider)

如需這個成員的說明,請參閱 ToInt32(IFormatProvider)

IConvertible.ToInt64(IFormatProvider)

如需這個成員的說明,請參閱 ToInt64(IFormatProvider)

IConvertible.ToSByte(IFormatProvider)

如需這個成員的說明,請參閱 ToSByte(IFormatProvider)

IConvertible.ToSingle(IFormatProvider)

如需這個成員的說明,請參閱 ToSingle(IFormatProvider)

IConvertible.ToType(Type, IFormatProvider)

如需這個成員的說明,請參閱 ToType(Type, IFormatProvider)

IConvertible.ToUInt16(IFormatProvider)

如需這個成員的說明,請參閱 ToUInt16(IFormatProvider)

IConvertible.ToUInt32(IFormatProvider)

如需這個成員的說明,請參閱 ToUInt32(IFormatProvider)

IConvertible.ToUInt64(IFormatProvider)

如需這個成員的說明,請參閱 ToUInt64(IFormatProvider)

IDecrementOperators<Double>.Decrement(Double)

遞減值。

IDivisionOperators<Double,Double,Double>.Division(Double, Double)

將一個值除以計算其商數。

IFloatingPoint<Double>.GetExponentByteCount()

取得將寫入為 的 TryWriteExponentLittleEndian(Span<Byte>, Int32) 位元組數目。

IFloatingPoint<Double>.GetExponentShortestBitLength()

取得目前指數之最短兩個補數標記法的長度,以位為單位。

IFloatingPoint<Double>.GetSignificandBitLength()

取得目前符號的長度,以位為單位。

IFloatingPoint<Double>.GetSignificandByteCount()

取得將寫入為 的 TryWriteSignificandLittleEndian(Span<Byte>, Int32) 位元組數目。

IFloatingPoint<Double>.TryWriteExponentBigEndian(Span<Byte>, Int32)

嘗試以大端格式將目前的指數寫入指定的範圍。

IFloatingPoint<Double>.TryWriteExponentLittleEndian(Span<Byte>, Int32)

嘗試以小到尾格式將目前的指數寫入指定的範圍。

IFloatingPoint<Double>.TryWriteSignificandBigEndian(Span<Byte>, Int32)

嘗試以大端格式將目前的 significand 寫入指定的範圍。

IFloatingPoint<Double>.TryWriteSignificandLittleEndian(Span<Byte>, Int32)

嘗試以小到尾格式將目前的 significand 寫入指定的範圍。

IFloatingPointConstants<Double>.E

取得數學常數 e

IFloatingPointConstants<Double>.Pi

取得數學常數 pi

IFloatingPointConstants<Double>.Tau

取得數學常數 tau

IFloatingPointIeee754<Double>.Epsilon

取得最小值,因此可以加入至 0 不會產生 的 0 最小值。

IFloatingPointIeee754<Double>.NaN

取得表示 的值 NaN

IFloatingPointIeee754<Double>.NegativeInfinity

取得值,表示負 infinity 值。

IFloatingPointIeee754<Double>.NegativeZero

取得值,表示負 zero 值。

IFloatingPointIeee754<Double>.PositiveInfinity

取得值,表示正 infinity

IIncrementOperators<Double>.Increment(Double)

遞增值。

IMinMaxValue<Double>.MaxValue

取得目前型別的最大值。

IMinMaxValue<Double>.MinValue

取得目前型別的最小值。

IModulusOperators<Double,Double,Double>.Modulus(Double, Double)

將兩個值分割在一起,以計算其模數或餘數。

IMultiplicativeIdentity<Double,Double>.MultiplicativeIdentity

取得目前型別的乘法識別。

IMultiplyOperators<Double,Double,Double>.Multiply(Double, Double)

將兩個值相乘以計算其產品。

INumberBase<Double>.IsCanonical(Double)

判斷值是否在其標準表示中。

INumberBase<Double>.IsComplexNumber(Double)

判斷值是否代表複數。

INumberBase<Double>.IsImaginaryNumber(Double)

判斷值是否代表純虛數。

INumberBase<Double>.IsZero(Double)

判斷值是否為零。

INumberBase<Double>.One

取得型別的值 1

INumberBase<Double>.Radix

取得類型的基數或基底。

INumberBase<Double>.TryConvertFromChecked<TOther>(TOther, Double)

表示雙精度浮點數。

INumberBase<Double>.TryConvertFromSaturating<TOther>(TOther, Double)

表示雙精度浮點數。

INumberBase<Double>.TryConvertFromTruncating<TOther>(TOther, Double)

表示雙精度浮點數。

INumberBase<Double>.TryConvertToChecked<TOther>(Double, TOther)

嘗試將目前型別的實例轉換成另一個型別,針對落在目前類型可表示範圍以外的任何值擲回溢位例外狀況。

INumberBase<Double>.TryConvertToSaturating<TOther>(Double, TOther)

嘗試將目前型別的實例轉換成另一個類型,使任何落在目前類型可表示範圍以外的值飽和。

INumberBase<Double>.TryConvertToTruncating<TOther>(Double, TOther)

嘗試將目前型別的實例轉換成另一個型別,並截斷任何落在目前類型之可表示範圍以外的值。

INumberBase<Double>.Zero

取得型別的值 0

ISignedNumber<Double>.NegativeOne

取得型別的值 -1

ISubtractionOperators<Double,Double,Double>.Subtraction(Double, Double)

減去兩個值來計算其差異。

IUnaryNegationOperators<Double,Double>.UnaryNegation(Double)

計算值的一元負數。

IUnaryPlusOperators<Double,Double>.UnaryPlus(Double)

計算值的一元加號。

適用於

執行緒安全性

此類型的所有成員都是安全線程。 看似修改實例狀態的成員,實際上會傳回以新值初始化的新實例。 如同任何其他類型,讀取和寫入包含此類型實例的共用變數必須受到鎖定保護,以確保執行緒安全。

另請參閱