The Decimal CompareTo method in C# is used to compare the current decimal value with the specified decimal value. It returns an integer value that indicates whether the current decimal value is less than, equal to, or greater than the specified decimal value.
Example 1: Comparing two decimal values
decimal num1 = 10.5m; decimal num2 = 20.5m; int result = num1.CompareTo(num2);
In this example, we have two decimal values num1 and num2. We are using the CompareTo method to compare these two values. The result will be -1 because num1 is less than num2.
Example 2: Sorting an array of decimal values
decimal[] arr = new decimal[] { 5.5m, 2.5m, 10.5m, 8.5m }; Array.Sort(arr); foreach(decimal val in arr) { Console.WriteLine(val); }
In this example, we have an array of decimal values. We are using the Sort method of the Array class to sort the array in ascending order. The CompareTo method is used internally by the Sort method to compare the values and sort them.
This method is part of the System namespace, which is included in the .NET Framework Class Library.
C# (CSharp) Decimal.CompareTo - 30 examples found. These are the top rated real world C# (CSharp) examples of Decimal.CompareTo extracted from open source projects. You can rate examples to help us improve the quality of examples.