Take the 2-minute tour ×

Possible Duplicate:
How to resolve a Java Rounding Double issue

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;


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?

share|improve this question

marked as duplicate by Matthew Farwell, artbristol, Peter Lawrey, Conrad Frix, ChrisF Nov 10 '11 at 20:56


This is because doubles and floats cannot express every numerical value. They are really using approximations to represent the value. –  onit Nov 10 '11 at 15:21
It is not a duplicate of that question. –  Tiny Mar 6 at 10:11

2 Answers 2

up vote 12 down vote accepted

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) {...}
share|improve this answer
You might want to take a look at the Double's compare method. Check this link : tutorialspoint.com/java/lang/double_compare.htm –  Tina Maria Jun 30 at 4:54

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

share|improve this answer
BigDecimal is sometimes not a viable solution. –  mcfinnigan Nov 10 '11 at 15:57
