Double.CompareTo Method in C# with Examples


The Double.CompareTo() method in C# is used to compare this instance to a specified object or Double 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 or Double object.

Syntax

The syntax is as follows −

public int CompareTo (double val);
public int CompareTo (object val);

Above, the value val in the 1st syntax is a double-precision floating-point number to compare, whereas val for the 2nd syntax is an object to compare.

Example

Let us now see an example −

 Live Demo

using System;
public class Demo {
   public static void Main() {
      double d1 = 150d;
      double d2 = 150d;
      Console.WriteLine("Double1 Value = "+d1);
      Console.WriteLine("Double2 Value = "+d2);
      Console.WriteLine("Are both the double values equal? = "+d1.CompareTo(d2));
   }
}

Output

This will produce the following output −

Double1 Value = 150
Double2 Value = 150
Are both the double values equal? = 0

Example

Let us now see another example −

 Live Demo

using System;
public class Demo {
   public static void Main() {
      double d1 = 20d;
      object d2 = 20d;
      Console.WriteLine("Double1 Value = "+d1);
      Console.WriteLine("Double2 Value = "+d2);
      Console.WriteLine("Are both the double values equal? = "+d1.CompareTo(d2));
   }
}

Output

This will produce the following output −

Double1 Value = 20
Double2 Value = 20
Are both the double values equal? = 0

Updated on: 04-Dec-2019

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements