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?
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).
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.
Your code will work as expected. C# decimal
s 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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With