Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare two double values in Java?

Tags:

java

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?

like image 396
Lion Avatar asked Nov 10 '11 15:11

Lion


People also ask

Can you use == to compare doubles in Java?

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.

Can you use compareTo with double?

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.

How do you compare doubles to strings?

s1 = Double. toString(dbVal1); s2 = Double. toString(dbVal2); if (s1. compareTo(s2)!=


2 Answers

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) {...} 
like image 87
Kevin Avatar answered Sep 20 '22 17:09

Kevin


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

like image 44
Zaki Saadeh Avatar answered Sep 16 '22 17:09

Zaki Saadeh