Double Structure
.NET Framework Class Library
Double Structure

Updated: May 2009

Represents a double-precision floating-point number.

Namespace:  System
Assembly:  mscorlib (in mscorlib.dll)
Visual Basic (Declaration)
<SerializableAttribute> _
<ComVisibleAttribute(True)> _
Public Structure Double _
    Implements IComparable, IFormattable, IConvertible, IComparable(Of Double),  _
    IEquatable(Of Double)
Visual Basic (Usage)
Dim instance As Double
C#
[SerializableAttribute]
[ComVisibleAttribute(true)]
public struct Double : IComparable, IFormattable, 
    IConvertible, IComparable<double>, IEquatable<double>
Visual C++
[SerializableAttribute]
[ComVisibleAttribute(true)]
public value class Double : IComparable, 
    IFormattable, IConvertible, IComparable<double>, IEquatable<double>
JScript
JScript supports the use of structures, but not the declaration of new ones.

The Double value type represents a double-precision 64-bit number with values ranging from negative 1.79769313486232e308 to positive 1.79769313486232e308, as well as positive or negative zero, PositiveInfinity, NegativeInfinity, and Not-a-Number (NaN).

Double complies with the IEC 60559:1989 (IEEE 754) standard for binary floating-point arithmetic.

Double provides methods to compare instances of this type, convert the value of an instance to its string representation, and convert the string representation of a number to an instance of this type. For information about how format specification codes control the string representation of value types, see Formatting Overview, Standard Numeric Format Strings, and Custom Numeric Format Strings.

Using Floating-Point Numbers

When performing binary operations, if one of the operands is a Double, then the other operand is required to be an integral type or a floating-point type (Double or Single). Prior to performing the operation, if the other operand is not a Double, it is converted to Double, and the operation is performed using at least Double range and precision. If the operation produces a numeric result, the type of the result is Double.

The floating-point operators, including the assignment operators, do not throw exceptions. Instead, in exceptional situations the result of a floating-point operation is zero, infinity, or NaN, as described below:

  • If the result of a floating-point operation is too small for the destination format, the result of the operation is zero.

  • If the magnitude of the result of a floating-point operation is too large for the destination format, the result of the operation is PositiveInfinity or NegativeInfinity, as appropriate for the sign of the result.

  • If a floating-point operation is invalid, the result of the operation is NaN.

  • If one or both operands of a floating-point operation are NaN, the result of the operation is NaN.

Remember that a floating-point number can only approximate a decimal number, and that the precision of a floating-point number determines how accurately that number approximates a decimal number. By default, a Double value contains 15 decimal digits of precision, although a maximum of 17 digits is maintained internally. The 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.

  • 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 floating-point number might not exactly approximate the decimal number.

  • A value might not roundtrip if a floating-point number is involved. A value is said to roundtrip 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 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.

Differences in Precision by Processor Architecture

In addition, the loss of precision that results from arithmetic, assignment, and parsing operations with Double values may differ by platform. 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.

Visual Basic
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      
C#
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      

Such differences by processor architecture are most likely to occur for values that are less than Epsilon. The following example attempts to parse the string "4.9E-324", which is a value slightly less than Epsilon. As the output from the example shows, it is rounded up to Epsilon on 32-bit platforms and rounded down to 0.0 on 64-bit platforms.

Visual Basic
Dim value As String = "4.9E-324"
Dim d As Double = Double.Parse(value)
Console.WriteLine("{0} -> {1}", value, d)
' The example displays the following output:
'    On 32-bit platforms:
'        4.9E-324 -> 4.94065645841247E-324
'    On 64-bit platforms:
'       4.9E-324 -> 0.0
C#
string value = "4.9E-324";
double d = Double.Parse(value);
Console.WriteLine("{0} -> {1}", value, d);
// The example displays the following output:
//    On 32-bit platforms:
//        4.9E-324 -> 4.94065645841247E-324
//    On 64-bit platforms:
//       4.9E-324 -> 0.0

If an application requires identical behavior across platforms, it should be compiled with the /platform:x86 switch so that it always runs on the 32-bit runtime regardless of processor architecture.

Interface Implementations

This type implements the interfaces IComparable, IComparable<(Of <(T>)>), IFormattable, and IConvertible. Use the Convert class for conversions instead of this type's explicit interface member implementation of IConvertible.

The following code example illustrates the use of Double:

Visual Basic
' 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
C#
    /// <summary>
    /// Temperature class stores the value as Double
    /// and delegates most of the functionality 
    /// to the Double implementation.
    /// </summary>
    public class Temperature : IComparable, IFormattable {
        /// <summary>
        /// IComparable.CompareTo implementation.
        /// </summary>
        public int CompareTo(object obj) {
            if(obj is Temperature) {
                Temperature temp = (Temperature) obj;

                return m_value.CompareTo(temp.m_value);
            }
            
            throw new ArgumentException("object is not a Temperature");    
        }

        /// <summary>
        /// IFormattable.ToString implementation.
        /// </summary>
        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);
        }

        /// <summary>
        /// Parses the temperature from a string in form
        /// [ws][sign]digits['F|'C][ws]
        /// </summary>
        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;
            }
        }
    }
Visual C++
/// <summary>
/// Temperature class stores the value as Double
/// and delegates most of the functionality 
/// to the Double implementation.
/// </summary>
public ref class Temperature: public IComparable, public IFormattable
{
   /// <summary>
   /// IComparable.CompareTo implementation.
   /// </summary>
public:
   virtual int CompareTo( Object^ obj )
   {
      if ( dynamic_cast<Temperature^>(obj) )
      {
         Temperature^ temp = (Temperature^)(obj);
         return m_value.CompareTo( temp->m_value );
      }

      throw gcnew ArgumentException( "object is not a Temperature" );
   }

   /// <summary>
   /// IFormattable.ToString implementation.
   /// </summary>
   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 );
   }


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

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

      return temp;
   }

protected:
   // The value holder
   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;
      }

   }

};
JScript
    /// <summary>
    /// Temperature class stores the value as Double
    /// and delegates most of the functionality 
    /// to the Double implementation.
    /// </summary>
    public class Temperature implements IComparable, IFormattable {
        /// <summary>
        /// IComparable.CompareTo implementation.
        /// </summary>
        public function CompareTo(obj) : int{
            if(obj.GetType() == Temperature) {
                var temp : Temperature = Temperature(obj);

                return m_value.CompareTo(temp.m_value);
            }
            
            throw new ArgumentException("object is not a Temperature");    
        }

        /// <summary>
        /// IFormattable.ToString implementation.
        /// </summary>
        public function ToString(format : String, provider : IFormatProvider) : String {
            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);
        }

        /// <summary>
        /// Parses the temperature from a string in form
        /// [ws][sign]digits['F|'C][ws]
        /// </summary>
        public static function Parse(s : String, styles : NumberStyles, provider : IFormatProvider) : Temperature{
            var temp : Temperature = 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 var m_value : double;

        public function get Value() : double{
            return m_value;
        }
        
                public function set Value(value : double) {
            m_value = value;
        }

        public function get Celsius() : double {
            return (m_value-32.0)/1.8;
                }

                public function set Celsius(value : double) {
            m_value = 1.8*value+32.0;
        }
    }

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.

Windows 7, Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98, Windows CE, Windows Mobile for Smartphone, Windows Mobile for Pocket PC, Xbox 360, Zune

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

.NET Framework

Supported in: 3.5, 3.0, 2.0, 1.1, 1.0

.NET Compact Framework

Supported in: 3.5, 2.0, 1.0

XNA Framework

Supported in: 3.0, 2.0, 1.0

Date

History

Reason

May 2009

Added information about platform differences for values less than Epsilon.

Content bug fix.

April 2009

Added information about platform differences in the precision of the Double type.

Content bug fix.

Tags What's this?: Add a tag
Community Content   What is Community Content?
Add new content RSS  Annotations
Processing
Page view tracker