Related Tags

c#
communitycreator

# How to compare two decimal values in C#

Theodore Kelechukwu Onyejiaku

### 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 System
using System;

// create class
class CompareDecimal
{
// main method
static void Main()
{
// create some
// decimal values
decimal 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 values
int a = Decimal.Compare(d1,d2);
int b = Decimal.Compare(d3,d4);
int c = Decimal.Compare(d5,d6);

// print returned values
System.Console.WriteLine(a);
System.Console.WriteLine(b);
System.Console.WriteLine(c);
}
}
Compare two decimal values in C# using the Decimal.Compare() method

### 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 -1 because d1 is less than d2.

• In line 26, our return value is 1 because d3 is greater than d4.

• In line 27, our return value is 0 because d5 and d6 are equal.

RELATED TAGS

c#
communitycreator

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time