Search code examples
javadouble

Compare double values


Here is code:

 double d1 = 2.4066419461049408E7;
 double d2 = 500.0;
 int retval = Double.compare(d1, d2);
    
 if(retval > 0) {
     System.out.println("d1 is greater than d2");
 } else if(retval < 0) {
     System.out.println("d1 is less than d2");
 } else {
     System.out.println("d1 is equal to d2");
 }

Output:

d1 is greater than d2

Why? How to get right answer?


Solution

  • This is the right answer: 2.4066419461049408E7 is (by far) greater than 500.0

    Notice the E7 at the end of the 1st number: this means x10^7 (exponent).

    You are thus comparing 24066419.461049408 to 500.0.