Skip to main content
.NET Framework Class Library
Double Structure

Represents a double-precision floating-point number.

Namespace:   System
Assembly:  mscorlib (in mscorlib.dll)
Syntax
<[%$TOPIC/643eft0t_en-us_VS_110_1_0_0_0_0%]> _
<[%$TOPIC/643eft0t_en-us_VS_110_1_0_0_0_1%](True)> _
Public Structure Double _
	Implements [%$TOPIC/643eft0t_en-us_VS_110_1_0_0_0_2%], [%$TOPIC/643eft0t_en-us_VS_110_1_0_0_0_3%], [%$TOPIC/643eft0t_en-us_VS_110_1_0_0_0_4%], [%$TOPIC/643eft0t_en-us_VS_110_1_0_0_0_5%](Of Double),  _
	[%$TOPIC/643eft0t_en-us_VS_110_1_0_0_0_6%](Of Double)
[[%$TOPIC/643eft0t_en-us_VS_110_1_0_1_0_0%]]
[[%$TOPIC/643eft0t_en-us_VS_110_1_0_1_0_1%](true)]
public struct Double : [%$TOPIC/643eft0t_en-us_VS_110_1_0_1_0_2%], [%$TOPIC/643eft0t_en-us_VS_110_1_0_1_0_3%], 
	[%$TOPIC/643eft0t_en-us_VS_110_1_0_1_0_4%], [%$TOPIC/643eft0t_en-us_VS_110_1_0_1_0_5%]<double>, [%$TOPIC/643eft0t_en-us_VS_110_1_0_1_0_6%]<double>
[[%$TOPIC/643eft0t_en-us_VS_110_1_0_2_0_0%]]
[[%$TOPIC/643eft0t_en-us_VS_110_1_0_2_0_1%](true)]
public value class Double : [%$TOPIC/643eft0t_en-us_VS_110_1_0_2_0_2%], 
	[%$TOPIC/643eft0t_en-us_VS_110_1_0_2_0_3%], [%$TOPIC/643eft0t_en-us_VS_110_1_0_2_0_4%], [%$TOPIC/643eft0t_en-us_VS_110_1_0_2_0_5%]<double>, [%$TOPIC/643eft0t_en-us_VS_110_1_0_2_0_6%]<double>
[<[%$TOPIC/643eft0t_en-us_VS_110_1_0_3_0_0%]>]
[<[%$TOPIC/643eft0t_en-us_VS_110_1_0_3_0_1%]>]
[<[%$TOPIC/643eft0t_en-us_VS_110_1_0_3_0_2%](true)>]
type Double =  
    struct 
        interface [%$TOPIC/643eft0t_en-us_VS_110_1_0_3_0_3%] 
        interface [%$TOPIC/643eft0t_en-us_VS_110_1_0_3_0_4%] 
        interface [%$TOPIC/643eft0t_en-us_VS_110_1_0_3_0_5%] 
        interface [%$TOPIC/643eft0t_en-us_VS_110_1_0_3_0_6%]<float>
        interface [%$TOPIC/643eft0t_en-us_VS_110_1_0_3_0_7%]<float>
    end
JScript supports the use of structures, but not the declaration of new ones.

The Double type exposes the following members.

Methods
  NameDescription
Public method Supported by the XNA Framework Supported by Portable Class Library CompareTo(Double)Compares this instance to a specified double-precision floating-point number and returns an integer that indicates whether the value of this instance is less than, equal to, or greater than the value of the specified double-precision floating-point number.
Public method Supported by the XNA Framework CompareTo(Object)Compares this instance to a specified object and returns an integer that indicates whether the value of this instance is less than, equal to, or greater than the value of the specified object.
Public method Supported by the XNA Framework Supported by Portable Class Library Equals(Double)Returns a value indicating whether this instance and a specified Double object represent the same value.
Public method Supported by the XNA Framework Supported by Portable Class Library Equals(Object)Returns a value indicating whether this instance is equal to a specified object. (Overrides ValueTypeEquals(Object).)
Public method Supported by the XNA Framework Supported by Portable Class Library GetHashCodeReturns the hash code for this instance. (Overrides ValueTypeGetHashCode.)
Public method Supported by the XNA Framework Supported by Portable Class Library GetTypeGets the Type of the current instance. (Inherited from Object.)
Public method Supported by the XNA Framework GetTypeCodeReturns the TypeCode for value type Double.
Public method Static member Supported by the XNA Framework Supported by Portable Class Library IsInfinityReturns a value indicating whether the specified number evaluates to negative or positive infinity
Public method Static member Supported by the XNA Framework Supported by Portable Class Library IsNaNReturns a value that indicates whether the specified value is not a number ( NaN).
Public method Static member Supported by the XNA Framework Supported by Portable Class Library IsNegativeInfinityReturns a value indicating whether the specified number evaluates to negative infinity.
Public method Static member Supported by the XNA Framework Supported by Portable Class Library IsPositiveInfinityReturns a value indicating whether the specified number evaluates to positive infinity.
Public method Static member Supported by the XNA Framework Supported by Portable Class Library Parse(String)Converts the string representation of a number to its double-precision floating-point number equivalent.
Public method Static member Supported by the XNA Framework Supported by Portable Class Library Parse(String, NumberStyles)Converts the string representation of a number in a specified style to its double-precision floating-point number equivalent.
Public method Static member Supported by the XNA Framework Supported by Portable Class Library Parse(String, IFormatProvider)Converts the string representation of a number in a specified culture-specific format to its double-precision floating-point number equivalent.
Public method Static member Supported by the XNA Framework Supported by Portable Class Library Parse(String, NumberStyles, IFormatProvider)Converts the string representation of a number in a specified style and culture-specific format to its double-precision floating-point number equivalent.
Public method Supported by the XNA Framework Supported by Portable Class Library ToStringConverts the numeric value of this instance to its equivalent string representation. (Overrides ValueTypeToString.)
Public method Supported by the XNA Framework Supported by Portable Class Library ToString(IFormatProvider)Converts the numeric value of this instance to its equivalent string representation using the specified culture-specific format information.
Public method Supported by the XNA Framework Supported by Portable Class Library ToString(String)Converts the numeric value of this instance to its equivalent string representation, using the specified format.
Public method Supported by the XNA Framework Supported by Portable Class Library ToString(String, IFormatProvider)Converts the numeric value of this instance to its equivalent string representation using the specified format and culture-specific format information.
Public method Static member Supported by Portable Class Library TryParse(String, Double)Converts the string representation of a number to its double-precision floating-point number equivalent. A return value indicates whether the conversion succeeded or failed.
Public method Static member Supported by Portable Class Library TryParse(String, NumberStyles, IFormatProvider, Double)Converts the string representation of a number in a specified style and culture-specific format to its double-precision floating-point number equivalent. A return value indicates whether the conversion succeeded or failed.
Top
Operators
  NameDescription
Public operator Static member Supported by Portable Class Library EqualityReturns a value that indicates whether two specified Double values are equal.
Public operator Static member Supported by Portable Class Library GreaterThanReturns a value that indicates whether a specified Double value is greater than another specified Double value.
Public operator Static member Supported by Portable Class Library GreaterThanOrEqualReturns a value that indicates whether a specified Double value is greater than or equal to another specified Double value.
Public operator Static member Supported by Portable Class Library InequalityReturns a value that indicates whether two specified Double values are not equal.
Public operator Static member Supported by Portable Class Library LessThanReturns a value that indicates whether a specified Double value is less than another specified Double value.
Public operator Static member Supported by Portable Class Library LessThanOrEqualReturns a value that indicates whether a specified Double value is less than or equal to another specified Double value.
Top
Fields
  NameDescription
Public field Static member Supported by the XNA Framework Supported by Portable Class Library EpsilonRepresents the smallest positive Double value that is greater than zero. This field is constant.
Public field Static member Supported by the XNA Framework Supported by Portable Class Library MaxValueRepresents the largest possible value of a Double. This field is constant.
Public field Static member Supported by the XNA Framework Supported by Portable Class Library MinValueRepresents the smallest possible value of a Double. This field is constant.
Public field Static member Supported by the XNA Framework Supported by Portable Class Library NaNRepresents a value that is not a number (NaN). This field is constant.
Public field Static member Supported by the XNA Framework Supported by Portable Class Library NegativeInfinityRepresents negative infinity. This field is constant.
Public field Static member Supported by the XNA Framework Supported by Portable Class Library PositiveInfinityRepresents positive infinity. This field is constant.
Top
Explicit Interface Implementations
  NameDescription
Explicit interface implemetation Private method Supported by Portable Class Library IComparableCompareToCompares 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 implemetation Private method Supported by the XNA Framework IConvertibleToBooleanInfrastructure. For a description of this member, see IConvertibleToBoolean.
Explicit interface implemetation Private method Supported by the XNA Framework IConvertibleToByteInfrastructure. For a description of this member, see IConvertibleToByte.
Explicit interface implemetation Private method Supported by the XNA Framework IConvertibleToCharInfrastructure. This conversion is not supported. Attempting to use this method throws an InvalidCastException.
Explicit interface implemetation Private method Supported by the XNA Framework IConvertibleToDateTimeInfrastructure. This conversion is not supported. Attempting to use this method throws an InvalidCastException
Explicit interface implemetation Private method Supported by the XNA Framework IConvertibleToDecimalInfrastructure. For a description of this member, see IConvertibleToDecimal.
Explicit interface implemetation Private method Supported by the XNA Framework IConvertibleToDoubleInfrastructure. For a description of this member, see IConvertibleToDouble.
Explicit interface implemetation Private method Supported by the XNA Framework IConvertibleToInt16Infrastructure. For a description of this member, see IConvertibleToInt16.
Explicit interface implemetation Private method Supported by the XNA Framework IConvertibleToInt32Infrastructure. For a description of this member, see IConvertibleToInt32.
Explicit interface implemetation Private method Supported by the XNA Framework IConvertibleToInt64Infrastructure. For a description of this member, see IConvertibleToInt64.
Explicit interface implemetation Private method Supported by the XNA Framework IConvertibleToSByteInfrastructure. For a description of this member, see IConvertibleToSByte.
Explicit interface implemetation Private method Supported by the XNA Framework IConvertibleToSingleInfrastructure. For a description of this member, see IConvertibleToSingle.
Explicit interface implemetation Private method Supported by the XNA Framework IConvertibleToTypeInfrastructure. For a description of this member, see IConvertibleToType.
Explicit interface implemetation Private method Supported by the XNA Framework IConvertibleToUInt16Infrastructure. For a description of this member, see IConvertibleToUInt16.
Explicit interface implemetation Private method Supported by the XNA Framework IConvertibleToUInt32Infrastructure. For a description of this member, see IConvertibleToUInt32.
Explicit interface implemetation Private method Supported by the XNA Framework IConvertibleToUInt64Infrastructure. For a description of this member, see IConvertibleToUInt64.
Top
Remarks

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

  • Testing for equality

  • Floating-point values and exceptions

  • Type conversions and the Double structure

  • Floating-point functionality

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 MathPI), 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.

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

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 DoubleEpsilon 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.

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

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.

    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).   
    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).   

    If you change the format items in the ConsoleWriteLine(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 MathRound(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.

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

    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.

    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:R}{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
    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:R}{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
  • 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.

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

    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.

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

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.

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

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.

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

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 MathRound 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.

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

    Note, though, that the problem of precision still applies to rounding of midpoint values. For more information, see the MathRound(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

    DoubleEpsilon is sometimes used as an absolute measure of the distance between two Double values when testing for equality. However, DoubleEpsilon 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 DoubleEpsilon 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.

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

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.

    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
    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
  • 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 DoubleMaxValue is PositiveInfinity, and the result of an operation that overflows DoubleMinValue is NegativeInfinity, as the following example shows.

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

    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 MathSqrt method with a negative value returns NaN, as does calling the MathAcos method with a value that is greater than one or less than negative one.

  • Any operation with an argument whose value is DoubleNaN.

Type conversions and the Double structure

The Double structure does not define any explicit or implicit conversion operators; instead, conversions are implemented by the compiler.

The conversion of the value of any primitive numeric type to a Double is a widening conversion and therefore does not require an explicit cast operator or call to a conversion method unless a compiler explicitly requires it. For example, the C# compiler requires a casting operator for conversions from Decimal to Double, while the Visual Basic compiler does not. The following example converts the minimum or maximum value of other primitive numeric types to a 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)
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)

In addition, the Single values SingleNaN, SinglePositiveInfinity, and SingleNegativeInfinity covert to DoubleNaN, DoublePositiveInfinity, and DoubleNegativeInfinity, respectively.

Note that the conversion of the value of some numeric types to a Double value can involve a loss of precision. As the example illustrates, a loss of precision is possible when converting Decimal, Int64, Single, and UInt64 values to Double values.

The conversion of a Double value to a value of any other primitive numeric data type is a narrowing conversion and requires a cast operator (in C#), a conversion method (in Visual Basic), or a call to a Convert method. Values that are outside the range of the target data type, which are defined by the target type's MinValue and MaxValue properties, behave as shown in the following table.

Target type

Result

Any integral type

An OverflowException exception if the conversion occurs in a checked context.

If the conversion occurs in an unchecked context (the default in C#), the conversion operation succeeds but the value overflows.

Decimal

An OverflowException exception.

Single

SingleNegativeInfinity for negative values.

SinglePositiveInfinity for positive values.

In addition, DoubleNaN, DoublePositiveInfinity, and DoubleNegativeInfinity throw an OverflowException for conversions to integers in a checked context, but these values overflow when converted to integers in an unchecked context. For conversions to Decimal, they always throw an OverflowException. For conversions to Single, they convert to SingleNaN, SinglePositiveInfinity, and SingleNegativeInfinity, respectively.

Note that a loss of precision may result from converting a Double value to another numeric type. In the case of converting non-integral Double values, as the output from the example shows, the fractional component is lost when the Double value is either rounded (as in Visual Basic) or truncated (as in C#). For conversions to Decimal and Single values, the Double value may not have a precise representation in the target data type.

The following example converts a number of Double values to several other numeric types. The conversions occur in a checked context in Visual Basic (the default) and in C# (because of the checked keyword). The output from the example shows the result for conversions in both a checked an unchecked context. You can perform conversions in an unchecked context in Visual Basic by compiling with the /removeintchecks+ compiler switch and in C# by commenting out the checked statement.

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)
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)

For more information on the conversion of numeric types, see Type Conversion in the .NET Framework and Type Conversion Tables in the .NET Framework.

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 SystemMath class. It includes additional methods commonly used for arithmetic (such as MathAbs, MathSign, and MathSqrt), geometry (such as MathCos and MathSin), and calculus (such as MathLog).

    You can also manipulate the individual bits in a Double value. The BitConverterDoubleToInt64Bits method preserves a Double value's bit pattern in a 64-bit integer. The BitConverterGetBytes(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 MathRound 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.

    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
    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
Examples

The following code example illustrates the use of Double:

' 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
// 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. 
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;
      }
   }
};
Version Information

.NET Framework

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

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

XNA Framework

Supported in: 3.0, 2.0, 1.0

Portable Class Library

Supported in: Portable Class Library

Supported in: Windows Phone 8.1

Supported in: Windows Phone Silverlight 8.1

Supported in: Windows Phone Silverlight 8
Thread Safety

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.