How to compare two decimal values in C#
Overview
The Decimal.Compare() method is used to compare two decimal numbers to see if one is greater than the other or if they are equal.
Suppose we have two decimal numbers, d1 and d2. If we compare them with Decimal.Compare(d1, d2), and d1 is less than d2, the return value is -1 (less than 0). The return value is 0 if d1 and d2 are equal. If d1 is greater than d2, the return value is 1 (greater than 0).
Syntax
Decimal.Compare(d1,d2)
Parameters
-
d1: The first of the decimal values we want to compare. -
d2: The second of the decimal values we want to compare.
Return value
The return value is an integer value from -1, 1, or 0.
Code example
// use Systemusing System;// create classclass CompareDecimal{// main methodstatic void Main(){// create some// decimal valuesdecimal d1 = 2.3m;decimal d2 = 3.1m;decimal d3 = 20.5m;decimal d4 = 12.6m;decimal d5 = 1.5m;decimal d6 = 1.5m;// compare decimal valuesint a = Decimal.Compare(d1,d2);int b = Decimal.Compare(d3,d4);int c = Decimal.Compare(d5,d6);// print returned valuesSystem.Console.WriteLine(a);System.Console.WriteLine(b);System.Console.WriteLine(c);}}
Explanation
In the code above:
-
In lines 12-17, we initialize six decimal variables.
-
In lines 20-22, we use the
Decimal.Compare()function to compare the decimal variables and assign the corresponding outputs to integer variables. -
In line 25, our return value is
-1becaused1is less thand2. -
In line 26, our return value is
1becaused3is greater thand4. -
In line 27, our return value is
0becaused5andd6are equal.