Compare Two Decimal Numbers to N Decimal Places

How do you compare two decimal values to ‘N’ decimal places. So for example, you want to compare two decimal numbers to 5 decimal places. Here’s an example:

C#

static void Main(string[] args)
{
decimal one = 23.5456533464M;
decimal two = 23.5456543444M;
decimal three = 23.5456223334M;

decimal a = Math.Truncate(one * 100000);
decimal b = Math.Truncate(two * 100000);
decimal c = Math.Truncate(three * 100000);
Console.WriteLine("Is Decimal One = Two?: {0}", Equals(a, b));
Console.WriteLine("Is Decimal Two = Three?: {0}", Equals(b, c));
Console.ReadLine();
}

VB.NET

Shared Sub Main(ByVal args() As String)
Dim one As Decimal = 23.5456533464D
Dim two As Decimal = 23.5456543444D
Dim three As Decimal = 23.5456223334D

Dim a As Decimal = Math.Truncate(one * 100000)
Dim b As Decimal = Math.Truncate(two * 100000)
Dim c As Decimal = Math.Truncate(three * 100000)
Console.WriteLine("Is Decimal One = Two?: {0}", Equals(a, b))
Console.WriteLine("Is Decimal Two = Three?: {0}", Equals(b, c))
Console.ReadLine()
End Sub

If you observe, we are multiplying each decimal by 5 zeros and considering only the integral part of the decimal using Math.Truncate.

The first two decimal numbers are equal considering the first 5 decimal places .54565. However the third decimal number is .54562, which is not equal to .54565 and hence the value printed is false

OUTPUT

image



Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

No comments: