1

I'm new to C# (Come from Java/C++ at uni so it's not really that new I guess) but for a project I'm needing to compare decimals.

e.g.

a = 1234.123
b = 1234.142

Decimal.Compare() will of course say they're not the same as a is smaller than b. What I want to do is compare it to that first decimal place (1 and 1) so it would return true.

The only way I've been able to think of is to convert it to use Decimal.GetBits() but I was hoping there is a simpler way I just haven't thought of yet.

slugster
  • 49,403
  • 14
  • 95
  • 145
KageOni
  • 7
  • 4

2 Answers2

1

You can round a decimal to one fractional digit and then compare them.

if (Decimal.Round(d1,1) == Decimal.Round(d2,1))
    Console.WriteLine("Close enough.");

And, if rounding (with default midpoint handling) is not what you want, Decimal types can also be used with all the other options, like those I covered in this earlier answer.

Community
  • 1
  • 1
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
-1

You can use Math.Truncate(Decimal) (MSDN)

Calculates the integral part of a specified decimal number.

Coding example.

Decimal a = 1234.123m;
Decimal b = 1234.142m;

Decimal A = Math.Truncate(a * 10);  
Console.WriteLine(A);// <= Will out 12341
Decimal B = Math.Truncate(b * 10); 
Console.WriteLine(B);// <= Will out 12341

Console.WriteLine(Decimal.Compare(A, B)); // Will out 0 ; A and B are equal. Which means a,b are equal to first decimal place

Note : This was tested and posted .

Also simple one line comparison :

Decimal a = 1234.123m;
Decimal b = 1234.142m;

 if(Decimal.Compare(Math.Truncate(a*10),Math.Truncate(b*10))==0){
      Console.WriteLine("Equal upto first decimal place"); // <= Will out this for a,b
 }
Kavindu Dodanduwa
  • 12,193
  • 3
  • 33
  • 46