比较两个小数 [英] Comparing two decimals

查看:88
本文介绍了比较两个小数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想比较c#中的两位小数和一定的误差范围。任何人都可以指出以下代码有问题。请注意,之后我对6个小数位感兴趣,因此可以忽略这些值。

I want to compare two decimals in c# with some margin of error. Can anyone point out problem with the following code. Note that I am interested in 6 decimal places after that I could ignore the values.

var valOne = decimal.Round(valueOne, 6);
var valTwo = decimal.Round(valueTwo, 6);
var difference = Math.Abs(valOne - valTwo);
if (difference > 0.0000001m) {
   Console.WriteLine("Values are different");
}
else {
    Console.WriteLine("Values are equal");
}

还是有更好的方法。

推荐答案

我认为,如果我不使用Round,那么此解决方案就可以了。

I think if I don't use Round then this solution is fine.

var valOne = 1.1234560M; // Decimal.Round(1.1234560M, 6);  Don't round.
var valTwo = 1.1234569M; // Decimal.Round(1.1234569M, 6);  Don't round

if (Math.Abs(valOne - valTwo) >= 0.000001M) // Six digits after decimal in epsilon
{
    Console.WriteLine("Values differ");
}
else
{
    Console.WriteLine("Values are the same");
}

如上所述,对于六个小数位,两个小数可以相差的最小值是0.000001M。小于此的任何值都可以安全地忽略。我认为此解决方案很好,但是如果有人认为我错过了某些事情,我感谢您的帮助。

As mentioned above for six decimal places the smallest amount the two decimals can differ is 0.000001M. Anything less than that can be safely ignored. I think this solution is fine but if anyone thinks I have missed something I appreciate your help.

谢谢

这篇关于比较两个小数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆