C# 比较 Double 和 Int 的最佳方法是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1650091/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 19:41:44  来源:igfitidea点击:

What's the best way to compare Double and Int?

c#doubleintequals

提问by Murat from Daminion Software

The following code in C# doesn't work:

C# 中的以下代码不起作用:

int iValue = 0;
double dValue = 0.0;

bool isEqual = iValue.Equals(dValue);

So, the question: what's the best way to compare Double and Int?

那么,问题是:比较 Double 和 Int 的最佳方法是什么?

采纳答案by LBushkin

You really can't compare floating point and integral values in a naive way; particularly, since there's the classic floating pointrepresentation challenges. What you cando is subtract one from the other and see if the difference between them is less than some precision you care about, like so:

你真的不能天真地比较浮点和整数值;特别是,因为有经典的浮点表示挑战。您可以做的是从另一个中减去一个,看看它们之间的差异是否小于您关心的某些精度,如下所示:

int iValue = 0;
double dValue = 0.0;

var diff = Math.Abs(dvalue - iValue);
if( diff < 0.0000001 ) // need some min threshold to compare floating points
   return true; // items equal

You really have to define for yourself what equalitymeans to you. For example, you may want a floating point value to round towards the nearest integer, so that 3.999999981 will be "equal" to 4. Or you may want to truncate the value, so it would effectively be 3. It all depends on what you're trying to achieve.

你真的必须自己定义什么对你来说equality意味着什么。例如,您可能希望浮点值向最接近的整数四舍五入,因此 3.999999981 将“等于”4。或者您可能想要截断该值,因此它实际上是 3。这一切都取决于您'正在努力实现。

EDIT:Note that i chose 0.0000001 as an example threshold value ... you need to decide for yourself what precision is sufficient for comparison. Just realize you need to be within the normal representational bounds of doublewhich I believe is defined as Double.Epsilon.

编辑:请注意,我选择 0.0000001 作为示例阈值......您需要自己决定什么精度足以进行比较。只是意识到您需要在double我认为定义为的正常表示范围内Double.Epsilon

回答by Ryan Brunner

This really depends on what you consider "equal". If you want your comparison to return true if and only if the double precisely matches the integer value (i.e. has no fractional component), you should cast your int to a double to do the comparison:

这实际上取决于您认为什么是“平等”。如果您希望您的比较在且仅当 double 与整数值精确匹配时返回 true(即没有小数部分),您应该将 int 转换为 double 以进行比较:

bool isEqual = (double)iValue == dValue;

If something like 1.1 would be considered equal to 1, you can either cast the double to an int (if you want to ignore the fractional component altogether) or round the double if you want say 1.9 to equal 2.

如果像 1.1 这样的东西被认为等于 1,你可以将 double 强制转换为 int(如果你想完全忽略小数部分),或者如果你想说 1.9 等于 2,则将 double 舍入。

回答by San Jacinto

It's an exceedingly bad idea to compare integers and floating-point numbers for equality in any language. It works for very simple cases, but after you do any math at all, the likliehood of the program doing what you want it to decreases dramatically.

在任何语言中比较整数和浮点数的相等性是一个非常糟糕的主意。它适用于非常简单的情况,但是在您进行任何数学运算之后,程序执行您希望它执行的操作的可能性会急剧下降。

It has to do with the way floating-point numbers are stored on a binary, digital system.

它与浮点数在二进制数字系统上的存储方式有关。

If you are very sure you want to use this, create a class to make you own number with fractions. use one int to maintain the whole number, and another int to maintain the fraction.

如果您非常确定要使用它,请创建一个类来让您拥有带分数的数字。使用一个 int 来保持整数,使用另一个 int 来保持分数。

回答by supercat

Nowadays, just about the only time one should be comparing values of types doubleand either integeror longfor strict equality is when, for some reason, one is stuck storing or passing integral quantities as floating-point values and later needs to convert them back. Such conversion may in most cases be most easily accomplished by casting the integral type to double, and then comparing the result of that cast. Note that conversion from longto doublemay be imprecise if the number is outside the range ±252. Nonetheless, in the days before 64-bit longbecame available, doublewas a handy storage type for integer quantities which were too big for a 32-bit intbut small enough to be handled by double.

如今,只是唯一的一次一个应该比较类型的值double,要么integerlong严格的平等时,由于某种原因,一个是存储卡或通过积分量为浮点值和以后需要将它们转换回来。在大多数情况下,通过将整数类型转换为double,然后比较该转换的结果,可以最容易地完成这种转换。请注意,如果数字超出范围 ±2 52,则从long到 的转换double可能不精确。尽管如此,在 64 位可用之前的日子里,对于整数来说,这是一种方便的存储类型,对于 32 位来说太大但小到.longdoubleintdouble

Note that converting a longto doubleand then doing the comparison will yield an "equal" result if the nominal value of the doubledoesn't precisely match the longvalue, but represents the closest possible doubleto that value. This behavior makes sense if one recognizes that floating-point types don't actually represent a single precise value, but rather a range of values.

请注意,如果 a 的标称值与该值不完全匹配,但表示最接近该值的可能,则将a 转换longdouble然后进行比较将产生“相等”结果。如果人们认识到浮点类型实际上并不表示单个精确值,而是表示一系列值,则这种行为是有意义的。doublelongdouble

回答by Jatin

double val1 = 0;
double val2 = 0.0;
if((val1 - Double.Epsilon) < 0)
{
    // Put your code here
}

      OR

if((val2 - Double.Epsilon) < 0)
{
    // Put your code here
}

where Double.Epsilon is lowest possible value for Double.

其中 Double.Epsilon 是 Double 的最低可能值。

回答by Milan Vylita

From https://docs.microsoft.com/en-us/dotnet/api/system.double.equals?view=netframework-4.8#System_Double_Equals_System_Double_

来自https://docs.microsoft.com/en-us/dotnet/api/system.double.equals?view=netframework-4.8#System_Double_Equals_System_Double_

Because Epsilon defines the minimum expression of a positive value whose range is near zero, the margin of difference between two similar values must be greater than Epsilon. Typically, it is many times greater than Epsilon. Because of this, we recommend that you do not use Epsilon when comparing Double values for equality.

由于 Epsilon 定义了范围接近零的正值的最小表达式,因此两个相似值之间的差值幅度必须大于 Epsilon。通常,它比 Epsilon 大很多倍。因此,我们建议您在比较 Double 值是否相等时不要使用 Epsilon。