A simple comparison of two double values in Java creates some problems. Let's consider the following simple code snippet in Java.
package doublecomparision;
final public class DoubleComparision
{
public static void main(String[] args)
{
double a = 1.000001;
double b = 0.000001;
System.out.println("
"+((a-b)==1.0));
}
}
The above code appears to return true
, the evaluation of the expression ((a-b)==1.0)
but it doesn't. It returns false
instead because the evaluation of this expression is 0.9999999999999999
which was actually expected to be 1.0
which is not equal to 1.0
hence, the condition evaluates to boolean false
. What is the best and suggested way to overcome such a situation?
Question&Answers:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…