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

No comments:

Post a Comment