如何正确比较C#十进制值? [英] How to properly compare decimal values in C#?
问题描述
我来自C ++背景,我知道,你不能准确地比较浮点数是否相等。对于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
}
如果如预期这不起作用,我愿意接受一个解决方案,它与误差幅度相等比较,说喜欢0.00001或类似的东西。什么是推荐的解决这个问题?
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?
推荐答案
按照预期的代码将工作。 C#小数
s的优化,是在代表基地10个数字很准确,所以如果这是你比较什么(钱,...),一切都应该罚款。
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.
下面是关于小数由Jon飞碟双向的准确度非常明确的解释:
Here's a very clear explanation about the accuracy of decimals by Jon Skeet:
这篇关于如何正确比较C#十进制值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!