Export (0) Print
Expand All

Double Structure

Represents a double-precision floating-point number.

Namespace:  System
Assembly:  mscorlib (in mscorlib.dll)

[SerializableAttribute]
[ComVisibleAttribute(true)]
public value class Double : IComparable, 
	IFormattable, IConvertible, IComparable<double>, IEquatable<double>

The Double type exposes the following members.

  NameDescription
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsCompareTo(Double)Compares this instance to a specified double-precision floating-point number and returns an integer that indicates whether the value of this instance is less than, equal to, or greater than the value of the specified double-precision floating-point number.
Public methodSupported by the XNA FrameworkCompareTo(Object)Compares this instance to a specified object and returns an integer that indicates whether the value of this instance is less than, equal to, or greater than the value of the specified object.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsEquals(Double)Returns a value indicating whether this instance and a specified Double object represent the same value.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsEquals(Object)Returns a value indicating whether this instance is equal to a specified object. (Overrides ValueType::Equals(Object).)
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsGetHashCodeReturns the hash code for this instance. (Overrides ValueType::GetHashCode().)
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsGetTypeGets the Type of the current instance. (Inherited from Object.)
Public methodSupported by the XNA FrameworkGetTypeCodeReturns the TypeCode for value type Double.
Public methodStatic memberSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsIsInfinityReturns a value indicating whether the specified number evaluates to negative or positive infinity
Public methodStatic memberSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsIsNaNReturns a value that indicates whether the specified value is not a number (NaN).
Public methodStatic memberSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsIsNegativeInfinityReturns a value indicating whether the specified number evaluates to negative infinity.
Public methodStatic memberSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsIsPositiveInfinityReturns a value indicating whether the specified number evaluates to positive infinity.
Public methodStatic memberSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsParse(String)Converts the string representation of a number to its double-precision floating-point number equivalent.
Public methodStatic memberSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsParse(String, NumberStyles)Converts the string representation of a number in a specified style to its double-precision floating-point number equivalent.
Public methodStatic memberSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsParse(String, IFormatProvider)Converts the string representation of a number in a specified culture-specific format to its double-precision floating-point number equivalent.
Public methodStatic memberSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsParse(String, NumberStyles, IFormatProvider)Converts the string representation of a number in a specified style and culture-specific format to its double-precision floating-point number equivalent.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsToString()Converts the numeric value of this instance to its equivalent string representation. (Overrides ValueType::ToString().)
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsToString(IFormatProvider)Converts the numeric value of this instance to its equivalent string representation using the specified culture-specific format information.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsToString(String)Converts the numeric value of this instance to its equivalent string representation, using the specified format.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsToString(String, IFormatProvider)Converts the numeric value of this instance to its equivalent string representation using the specified format and culture-specific format information.
Public methodStatic memberSupported by Portable Class LibrarySupported in .NET for Windows Store appsTryParse(String, Double%)Converts the string representation of a number to its double-precision floating-point number equivalent. A return value indicates whether the conversion succeeded or failed.
Public methodStatic memberSupported by Portable Class LibrarySupported in .NET for Windows Store appsTryParse(String, NumberStyles, IFormatProvider, Double%)Converts the string representation of a number in a specified style and culture-specific format to its double-precision floating-point number equivalent. A return value indicates whether the conversion succeeded or failed.
Top

  NameDescription
Public operatorStatic memberSupported by Portable Class LibrarySupported in .NET for Windows Store appsEqualityReturns a value that indicates whether two specified Double values are equal.
Public operatorStatic memberSupported by Portable Class LibrarySupported in .NET for Windows Store appsGreaterThanReturns a value that indicates whether a specified Double value is greater than another specified Double value.
Public operatorStatic memberSupported by Portable Class LibrarySupported in .NET for Windows Store appsGreaterThanOrEqualReturns a value that indicates whether a specified Double value is greater than or equal to another specified Double value.
Public operatorStatic memberSupported by Portable Class LibrarySupported in .NET for Windows Store appsInequalityReturns a value that indicates whether two specified Double values are not equal.
Public operatorStatic memberSupported by Portable Class LibrarySupported in .NET for Windows Store appsLessThanReturns a value that indicates whether a specified Double value is less than another specified Double value.
Public operatorStatic memberSupported by Portable Class LibrarySupported in .NET for Windows Store appsLessThanOrEqualReturns a value that indicates whether a specified Double value is less than or equal to another specified Double value.
Top

  NameDescription
Public fieldStatic memberSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsEpsilonRepresents the smallest positive Double value that is greater than zero. This field is constant.
Public fieldStatic memberSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsMaxValueRepresents the largest possible value of a Double. This field is constant.
Public fieldStatic memberSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsMinValueRepresents the smallest possible value of a Double. This field is constant.
Public fieldStatic memberSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsNaNRepresents a value that is not a number (NaN). This field is constant.
Public fieldStatic memberSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsNegativeInfinityRepresents negative infinity. This field is constant.
Public fieldStatic memberSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsPositiveInfinityRepresents positive infinity. This field is constant.
Top

  NameDescription
Explicit interface implemetationPrivate methodSupported by Portable Class LibrarySupported in .NET for Windows Store appsIComparable::CompareToCompares the current instance with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other object.
Explicit interface implemetationPrivate methodSupported by the XNA FrameworkIConvertible::ToBooleanInfrastructure. For a description of this member, see IConvertible::ToBoolean.
Explicit interface implemetationPrivate methodSupported by the XNA FrameworkIConvertible::ToByteInfrastructure. For a description of this member, see IConvertible::ToByte.
Explicit interface implemetationPrivate methodSupported by the XNA FrameworkIConvertible::ToCharInfrastructure. This conversion is not supported. Attempting to use this method throws an InvalidCastException.
Explicit interface implemetationPrivate methodSupported by the XNA FrameworkIConvertible::ToDateTimeInfrastructure. This conversion is not supported. Attempting to use this method throws an InvalidCastException
Explicit interface implemetationPrivate methodSupported by the XNA FrameworkIConvertible::ToDecimalInfrastructure. For a description of this member, see IConvertible::ToDecimal.
Explicit interface implemetationPrivate methodSupported by the XNA FrameworkIConvertible::ToDoubleInfrastructure. For a description of this member, see IConvertible::ToDouble.
Explicit interface implemetationPrivate methodSupported by the XNA FrameworkIConvertible::ToInt16Infrastructure. For a description of this member, see IConvertible::ToInt16.
Explicit interface implemetationPrivate methodSupported by the XNA FrameworkIConvertible::ToInt32Infrastructure. For a description of this member, see IConvertible::ToInt32.
Explicit interface implemetationPrivate methodSupported by the XNA FrameworkIConvertible::ToInt64Infrastructure. For a description of this member, see IConvertible::ToInt64.
Explicit interface implemetationPrivate methodSupported by the XNA FrameworkIConvertible::ToSByteInfrastructure. For a description of this member, see IConvertible::ToSByte.
Explicit interface implemetationPrivate methodSupported by the XNA FrameworkIConvertible::ToSingleInfrastructure. For a description of this member, see IConvertible::ToSingle.
Explicit interface implemetationPrivate methodSupported by the XNA FrameworkIConvertible::ToTypeInfrastructure. For a description of this member, see IConvertible::ToType.
Explicit interface implemetationPrivate methodSupported by the XNA FrameworkIConvertible::ToUInt16Infrastructure. For a description of this member, see IConvertible::ToUInt16.
Explicit interface implemetationPrivate methodSupported by the XNA FrameworkIConvertible::ToUInt32Infrastructure. For a description of this member, see IConvertible::ToUInt32.
Explicit interface implemetationPrivate methodSupported by the XNA FrameworkIConvertible::ToUInt64Infrastructure. For a description of this member, see IConvertible::ToUInt64.
Top

The Double value type represents a double-precision 64-bit number with values ranging from negative 1.79769313486232e308 to positive 1.79769313486232e308, as well as positive or negative zero, PositiveInfinity, NegativeInfinity, and not a number (NaN). It is intended to represent values that are extremely large (such as distances between planets or galaxies) or extremely small (the molecular mass of a substance in kilograms) and that often are imprecise (such as the distance from earth to another solar system), The Double type complies with the IEC 60559:1989 (IEEE 754) standard for binary floating-point arithmetic.

This topic consists of the following sections:

Floating-Point Representation and Precision

The Double data type stores double-precision floating-point values in a 64-bit binary format, as shown in the following table:

Part

Bits

Significand or mantissa

0-51

Exponent

52-62

Sign (0 = Positive, 1 = Negative)

63

Just as decimal fractions are unable to precisely represent some fractional values (such as 1/3 or Math::PI), binary fractions are unable to represent some fractional values. For example, 1/10, which is represented precisely by .1 as a decimal fraction, is represented by .001100110011 as a binary fraction, with the pattern "0011" repeating to infinity. In this case, the floating-point value provides an imprecise representation of the number that it represents. Performing additional mathematical operations on the original floating-point value often tends to increase its lack of precision. For example, if we compare the result of multiplying .1 by 10 and adding .1 to .1 nine times, we see that addition, because it has involved eight more operations, has produced the less precise result. Note that this disparity is apparent only if we display the two Double values by using the "R" standard numeric format string, which if necessary displays all 17 digits of precision supported by the Double type.

No code example is currently available or this language may not be supported.

Because some numbers cannot be represented exactly as fractional binary values, floating-point numbers can only approximate real numbers.

All floating-point numbers also have a limited number of significant digits, which also determines how accurately a floating-point value approximates a real number. A Double value has up to 15 decimal digits of precision, although a maximum of 17 digits is maintained internally. This means that some floating-point operations may lack the precision to change a floating point value. The following example provides an illustration. It defines a very large floating-point value, and then adds the product of Double::Epsilon and one quadrillion to it. The product, however, is too small to modify the original floating-point value. Its least significant digit is thousandths, whereas the most significant digit in the product is 1-312.

No code example is currently available or this language may not be supported.

The limited precision of a floating-point number has several consequences:

  • Two floating-point numbers that appear equal for a particular precision might not compare equal because their least significant digits are different. In the following example, a series of numbers are added together, and their total is compared with their expected total. Although the two values appear to be the same, a call to the Equals method indicates that they are not.

    No code example is currently available or this language may not be supported.

    If you change the format items in the Console::WriteLine(String, Object, Object) statement from {0} and {1} to {0:R} and {1:R} to display all significant digits of the two Double values, it is clear that the two values are unequal because of a loss of precision during the addition operations. In this case, the issue can be resolved by calling the Math::Round(Double, Int32) method to round the Double values to the desired precision before performing the comparison.

  • A mathematical or comparison operation that uses a floating-point number might not yield the same result if a decimal number is used, because the binary floating-point number might not equal the decimal number. A previous example illustrated this by displaying the result of multiplying .1 by 10 and adding .1 times.

    When accuracy in numeric operations with fractional values is important, you can use the Decimal rather than the Double type. When accuracy in numeric operations with integral values beyond the range of the Int64 or UInt64 types is important, use the BigInteger type.

  • A value might not round-trip if a floating-point number is involved. A value is said to round-trip if an operation converts an original floating-point number to another form, an inverse operation transforms the converted form back to a floating-point number, and the final floating-point number is not equal to the original floating-point number. The roundtrip might fail because one or more least significant digits are lost or changed in a conversion. In the following example, three Double values are converted to strings and saved in a file. As the output shows, however, even though the values appear to be identical, the restored values are not equal to the original values.

    No code example is currently available or this language may not be supported.

    In this case, the values can be successfully round-tripped by using the "R" standard numeric format string to preserve the full precision of Double values, as the following example shows.

    No code example is currently available or this language may not be supported.
  • Single values have less precision than Double values. A Single value that is converted to a seemingly equivalent Double often does not equal the Double value because of differences in precision. In the following example, the result of identical division operations is assigned to a Double and a Single value. After the Single value is cast to a Double, a comparison of the two values shows that they are unequal.

    No code example is currently available or this language may not be supported.

    To avoid this problem, use either the Double in place of the Single data type, or use the Round method so that both values have the same precision.

In addition, the result of arithmetic and assignment operations with Double values may differ slightly by platform because of the loss of precision of the Double type. For example, the result of assigning a literal Double value may differ in the 32-bit and 64-bit versions of the .NET Framework. The following example illustrates this difference when the literal value -4.42330604244772E-305 and a variable whose value is -4.42330604244772E-305 are assigned to a Double variable. Note that the result of the Parse(String) method in this case does not suffer from a loss of precision.

No code example is currently available or this language may not be supported.

Testing for Equality

To be considered equal, two Double values must represent identical values. However, because of differences in precision between values, or because of a loss of precision by one or both values, floating-point values that are expected to be identical often turn out to be unequal because of differences in their least significant digits. As a result, calls to the Equals method to determine whether two values are equal, or calls to the CompareTo method to determine the relationship between two Double values, often yield unexpected results. This is evident in the following example, where two apparently equal Double values turn out to be unequal because the first has 15 digits of precision, while the second has 17.

No code example is currently available or this language may not be supported.

Calculated values that follow different code paths and that are manipulated in different ways often prove to be unequal. In the following example, one Double value is squared, and then the square root is calculated to restore the original value. A second Double is multiplied by 3.51 and squared before the square root of the result is divided by 3.51 to restore the original value. Although the two values appear to be identical, a call to the Equals(Double) method indicates that they are not equal. Using the "R" standard format string to return a result string that displays all the significant digits of each Double value shows that the second value is .0000000000001 less than the first.

No code example is currently available or this language may not be supported.

In cases where a loss of precision is likely to affect the result of a comparison, you can adopt any of the following alternatives to calling the Equals or CompareTo method:

  • Call the Math::Round method to ensure that both values have the same precision. The following example modifies a previous example to use this approach so that two fractional values are equivalent.

    No code example is currently available or this language may not be supported.

    Note, though, that the problem of precision still applies to rounding of midpoint values. For more information, see the Math::Round(Double, Int32, MidpointRounding) method.

  • Test for approximate equality rather than equality. This requires that you define either an absolute amount by which the two values can differ but still be equal, or that you define a relative amount by which the smaller value can diverge from the larger value.

    Caution noteCaution

    Double::Epsilon is sometimes used as an absolute measure of the distance between two Double values when testing for equality. However, Double::Epsilon measures the smallest possible value that can be added to, or subtracted from, a Double whose value is zero. For most positive and negative Double values, the value of Double::Epsilon is too small to be detected. Therefore, except for values that are zero, we do not recommend its use in tests for equality.

    The following example uses the latter approach to define an IsApproximatelyEqual method that tests the relative difference between two values. It also contrasts the result of calls to the IsApproximatelyEqual method and the Equals(Double) method.

    No code example is currently available or this language may not be supported.

Floating-Point Values and Exceptions

Unlike operations with integral types, which throw exceptions in cases of overflow or illegal operations such as division by zero, operations with floating-point values do not throw exceptions. Instead, in exceptional situations, the result of a floating-point operation is zero, positive infinity, negative infinity, or not a number (NaN):

  • If the result of a floating-point operation is too small for the destination format, the result is zero. This can occur when two very small numbers are multiplied, as the following example shows.

    No code example is currently available or this language may not be supported.
  • If the magnitude of the result of a floating-point operation exceeds the range of the destination format, the result of the operation is PositiveInfinity or NegativeInfinity, as appropriate for the sign of the result. The result of an operation that overflows Double::MaxValue is PositiveInfinity, and the result of an operation that overflows Double::MinValue is NegativeInfinity, as the following example shows.

    No code example is currently available or this language may not be supported.

    PositiveInfinity also results from a division by zero with a positive dividend, and NegativeInfinity results from a division by zero with a negative dividend.

  • If a floating-point operation is invalid, the result of the operation is NaN. For example, NaN results from the following operations:

  • Any floating-point operation with an invalid input. For example, calling the Math::Sqrt method with a negative value returns NaN, as does calling the Math::Acos method with a value that is greater than one or less than negative one.

  • Any operation with an argument whose value is Double::NaN.

Floating-Point Functionality

The Double structure and related types provide methods to perform operations in the following areas:

  • Comparison of values. You can call the Equals method to determine whether two Double values are equal, or the CompareTo method to determine the relationship between two values.

    The Double structure also supports a complete set of comparison operators. For example, you can test for equality or inequality, or determine whether one value is greater than or equal to another. If one of the operands is a numeric type other than a Double, it is converted to a Double before performing the comparison.

    Caution noteCaution

    Because of differences in precision, two Double values that you expect to be equal may turn out to be unequal, which affects the result of the comparison. See the Testing for Equality section for more information about comparing two Double values.

    You can also call the IsNaN, IsInfinity, IsPositiveInfinity, and IsNegativeInfinity methods to test for these special values.

  • Mathematical operations. Common arithmetic operations, such as addition, subtraction, multiplication, and division, are implemented by language compilers and Common Intermediate Language (CIL) instructions, rather than by Double methods. If one of the operands in a mathematical operation is a numeric type other than a Double, it is converted to a Double before performing the operation. The result of the operation is also a Double value.

    Other mathematical operations can be performed by calling static (Shared in Visual Basic) methods in the System::Math class. It includes additional methods commonly used for arithmetic (such as Math::Abs, Math::Sign, and Math::Sqrt), geometry (such as Math::Cos and Math::Sin), and calculus (such as Math::Log).

    You can also manipulate the individual bits in a Double value. The BitConverter::DoubleToInt64Bits method preserves a Double value's bit pattern in a 64-bit integer. The BitConverter::GetBytes(Double) method returns its bit pattern in a byte array.

  • Rounding. Rounding is often used as a technique for reducing the impact of differences between values caused by problems of floating-point representation and precision. You can round a Double value by calling the Math::Round method.

  • Formatting. You can convert a Double value to its string representation by calling the ToString method or by using the composite formatting feature. For information about how format strings control the string representation of floating-point values, see the Standard Numeric Format Strings and Custom Numeric Format Strings topics.

  • Parsing strings. You can convert the string representation of a floating-point value to a Double value by calling either the Parse or TryParse method. If the parse operation fails, the Parse method throws an exception, whereas the TryParse method returns false.

  • Type conversion. The Double structure provides an explicit interface implementation for the IConvertible interface, which supports conversion between any two standard .NET Framework data types. Language compilers also support the implicit conversion of values of all other standard numeric types to Double values. Conversion of a value of any standard numeric type to a Double is a widening conversion and does not require the user of a casting operator or conversion method,

    However, conversion of Int64 and Single values can involve a loss of precision. The following table lists the differences in precision for each of these types:

    Type

    Maximum precision

    Internal precision

    Double

    15

    17

    Int64

    19 decimal digits

    19 decimal digits

    Single

    7 decimal digits

    9 decimal digits

    The problem of precision most frequently affects Single values that are converted to Double values. In the following example, two values produced by identical division operations are unequal because one of the values is a a single-precision floating point value converted to a Double.

    No code example is currently available or this language may not be supported.

The following code example illustrates the use of Double:

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

      if (dynamic_cast<Temperature^>(obj) )
      {
         Temperature^ temp = (Temperature^)(obj);
         return m_value.CompareTo( temp->m_value );
      }
      throw gcnew ArgumentException( "object is not a Temperature" );
   }

   // IFormattable.ToString implementation. 
   virtual String^ ToString( String^ format, IFormatProvider^ provider )
   {
      if ( format != nullptr )
      {
         if ( format->Equals( "F" ) )
         {
            return String::Format( "{0}'F", this->Value.ToString() );
         }

         if ( format->Equals( "C" ) )
         {
            return String::Format( "{0}'C", this->Celsius.ToString() );
         }
      }
      return m_value.ToString( format, provider );
   }

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

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

protected:
   double m_value;

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

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

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

      void set( double value )
      {
         m_value = 1.8 * value + 32.0;
      }
   }
};

.NET Framework

Supported in: 4.6, 4.5, 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Portable Class Library

Supported in: Portable Class Library

.NET for Windows Store apps

Supported in: Windows 8

Supported in: Windows Phone 8.1

Supported in: Windows Phone Silverlight 8.1

Supported in: Windows Phone Silverlight 8

Windows Phone 8.1, Windows Phone 8, Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

All members of this type are thread safe. Members that appear to modify instance state actually return a new instance initialized with the new value. As with any other type, reading and writing to a shared variable that contains an instance of this type must be protected by a lock to guarantee thread safety.

Caution noteCaution

Assigning an instance of this type is not thread safe on all hardware platforms because the binary representation of that instance might be too large to assign in a single atomic operation.

Show:
© 2014 Microsoft