简体   繁体   中英

Compare decimals to 1 decimal point?

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.

eg

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.

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 .

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
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM