Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
555 views
in Technique[技术] by (71.8m points)

comparison - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...