Single.CompareTo() Method in C# with Examples


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

The return value is less than zero if the 1st instance is less than 2nd. The return value is 0 if both are equal and greater than zero is 0, if the 1st instance is more than 2nd.

Synchronized

The syntaxes are as follows −

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

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

Example

Let us now see an example −

 Live Demo

using System;
public class Demo {
   public static void Main(){
      float f1 = 50.7f;
      float f2 = 50.7f;
      Console.WriteLine("Value1 = "+f1);
      Console.WriteLine("Value1 = "+f2);
      Console.WriteLine("Is f1 and f2 equal? = "+f1.CompareTo(f2));
   }
}

Output

This will produce the following output −

Value1 = 50.7
Value1 = 50.7
Is f1 and f2 equal? = 0

Example

Let us now see another example −

 Live Demo

using System;
public class Demo {
   public static void Main(){
      float f1 = 50.7f;
      object f2 = 50.7f;
      Console.WriteLine("Value1 = "+f1);
      Console.WriteLine("Value1 = "+f2);
      int res = f1.CompareTo(f2);
      if (res > 0)
         Console.WriteLine("f1 > f2");
      else if (res < 0)
         Console.WriteLine("f1 < f2");
      else
         Console.WriteLine("f1 = f2");
   }
}

Output

This will produce the following output −

Value1 = 50.7
Value1 = 50.7
f1 = f2

Updated on: 03-Dec-2019

144 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements