Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly compare decimal values in C#?

I come from a background in C++, and I know that you cannot accurately compare floats for equality. For C#, I simply assumed the same policy applies to decimal values, or any floating point value in general.

Basically, I have two decimal values and if they are NOT equal to each other, I need to perform some action. e.g.:

decimal value1, value2; // Assume value1 and value2 are set somewhere to valid values. if( value1 != value2 ) {     // Do something } 

If this doesn't work as expected, I'm willing to accept a solution that does an equality comparison with a margin of error, say like .00001 or something like that. What would be the recommended solution to this problem?

like image 711
void.pointer Avatar asked May 09 '11 17:05

void.pointer


People also ask

How can I compare two decimal numbers in C#?

Compare() method is used to compare two decimal numbers to see if one is greater than the other or if they are equal. Suppose we have two decimal numbers, d1 and d2 . If we compare them with Decimal. Compare(d1, d2) , and d1 is less than d2 , the return value is -1 (less than 0).

How do you know which decimal is bigger or smaller?

The greater a decimal is, the closer it is to one whole. The smaller a decimal is the farther it is from one whole. The first thing you need to look at is the digit number in each decimal. These each have two digits in them, so you can compare them right away.


1 Answers

Your code will work as expected. C# decimals are optimized to be very accurate at representing base 10 numbers, so if that's what you're comparing (money, ...), everything should be fine.

Here's a very clear explanation about the accuracy of decimals by Jon Skeet:

Difference between decimal, float and double in .NET?

like image 159
fretje Avatar answered Sep 25 '22 18:09

fretje