Double.CompareTo Method (Object)




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

Public Function CompareTo (
	value As Object
) As Integer


Type: System.Object

An object to compare, or null.

Return Value

Type: System.Int32




A negative integer

This instance is less than value.




This instance is equal to value.


This instance and value are both Double.NaN, PositiveInfinity, or NegativeInfinity

A positive integer

This instance is greater than value.




value is null.

Exception Condition

value is not a Double.

The value parameter must be null or an instance of Double; otherwise, an exception is thrown. Any instance of Double, regardless of its value, is considered greater than null.

Values must be identical to be considered equal. Particularly when floating-point values depend on multiple mathematical operations, it is common for them to lose precision and for their values to be nearly identical except for their least significant digits. Because of this, the return value of the CompareTo method at times may seem surprising. For example, multiplication by a particular value followed by division by the same value should produce the original value. In the following example, however, the computed value turns out to be greater than the original value. Showing all significant digits of the two values by using the "R" standard numeric format string indicates that the computed value differs from the original value in its least significant digits. For information on handling such comparisons, see the Remarks section of the Equals(Double) method.

Module Example
   Public Sub Main()
       Dim value1 As Double = 6.185
       Dim value2 As Object = value1 * .1 / .1
       Console.WriteLine("Comparing {0} and {1}: {2}",
                         value1, value2, value1.CompareTo(value2))
       Console.WriteLine("Comparing {0:R} and {1:R}: {2}",
                         value1, value2, value1.CompareTo(value2))
   End Sub
End Module
' The example displays the following output:
'       Comparing 6.185 and 6.185: -1
'       Comparing 6.185 and 6.1850000000000005: -1



The following code example illustrates the use of CompareTo in the context of Double.

Obj1 = CType(450, Double)

If A.CompareTo(Obj1) < 0 Then
    Console.WriteLine(A.ToString() + " is less than " + Obj1.ToString() + ".")
End If

If (A.CompareTo(Obj1) > 0) Then
    Console.WriteLine(A.ToString() + " is greater than " + Obj1.ToString() + ".")
End If

If (A.CompareTo(Obj1) = 0) Then
    Console.WriteLine(A.ToString() + " equals " + Obj1.ToString() + ".")
End If

.NET Framework
Available since 1.1
Available since 2.0
Windows Phone Silverlight
Available since 7.0
Return to top