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("\n"+((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?
Using the == Operator As a result, we can't have an exact representation of most double values in our computers. They must be rounded to be saved. In that case, comparing both values with the == operator would produce a wrong result.
CompareTo(Double) Compares this instance to a specified double-precision floating-point number and returns an integer that indicates whether the value of this instance is less than, equal to, or greater than the value of the specified double-precision floating-point number.
s1 = Double. toString(dbVal1); s2 = Double. toString(dbVal2); if (s1. compareTo(s2)!=
Basically you shouldn't do exact comparisons, you should do something like this:
double a = 1.000001; double b = 0.000001; double c = a-b; if (Math.abs(c-1.0) <= 0.000001) {...}
Instead of using doubles for decimal arithemetic, please use java.math.BigDecimal. It would produce the expected results.
For reference take a look at this stackoverflow question
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With