jQuery and ASP.NET

December 15, 2009

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



'Like' us on our FaceBook page if you find this blog useful. Thanks!


Did you like this post?
kick it on DotNetKicks.com Save on Delicious
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP 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 has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

comments

0 Responses to "Compare Two Decimal Numbers to N Decimal Places"
 

Copyright © 2009-2011 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions