Comparing double values in C#

2018-12-31 16:04发布

I've a double variable called x. In the code, x gets assigned a value of 0.1 and I check it in an 'if' statement comparing x and 0.1

if (x==0.1)
{
----
}

Unfortunately it does not enter the if statement

  1. Should I use Double or double?

  2. What's the reason behind this? Can you suggest a solution for this?

标签: c# .net double
15条回答
素衣白纱
2楼-- · 2018-12-31 16:37

double and Double are the same (double is an alias for Double) and can be used interchangeably.

The problem with comparing a double with another value is that doubles are approximate values, not exact values. So when you set x to 0.1 it may in reality be stored as 0.100000001 or something like that.

Instead of checking for equality, you should check that the difference is less than a defined minimum difference (tolerance). Something like:

if (Math.Abs(x - 0.1) < 0.0000001)
{
    ...
}
查看更多
人气声优
3楼-- · 2018-12-31 16:37

Comparing floating point number can't always be done precisely because of rounding. To compare

(x == .1)

the computer really compares

(x - .1) vs 0

Result of sybtraction can not always be represeted precisely because of how floating point number are represented on the machine. Therefore you get some nonzero value and the condition evaluates to false.

To overcome this compare

Math.Abs(x- .1) vs some very small threshold ( like 1E-9)
查看更多
美炸的是我
4楼-- · 2018-12-31 16:37

Double and double are identical.

For the reason, see http://www.yoda.arachsys.com/csharp/floatingpoint.html . In short: a double is not an exact type and a minute difference between "x" and "0.1" will throw it off.

查看更多
登录 后发表回答