0

I have this:

double a = ...;
double b = ...;
if (a < b) {
    ....
} else
....

But I cannot use this approach with floating points (double) because, for example:

double a = 5 - 4.9 = 0.999999964;
double b = 0.1;
a < b = true // when it should be false

I was thinking in two possible solutions

  • The first one using multiplying by a certain number, casting to int and rounding:

    (int) Math.round(a * 10_000) < (int) Math.round(b * 10_000);

  • Or using an epsilon in this way:

    double decimaPrecision = 0.00001; double max = Math.max(a, b); double min = Math.min(a, b); return Math.abs(a/ b) > (1.0 + decimaPrecision);

What approach shall I use? Do you knowa better way of checking this? Do you know any 3pp which does these kind of stuffs?

Manuelarte
  • 1,658
  • 2
  • 28
  • 47
  • 2
    +1, Good, fair question. It **always** depends on your particular use case. Could you post up some more context? – Bathsheba Sep 18 '14 at 10:28
  • 2
    Are you sure that `5 - 4.9` comes out as = `0.999999964`? Please double check that. – Bathsheba Sep 18 '14 at 10:30
  • @RuchiraGayanRanaweera I am not checking that a == b... That's the difference – Manuelarte Sep 18 '14 at 10:52
  • @Manuelarte: It's not an important difference. `<` and `>` and `<=` and `>=` work fine for `double`s. See also http://stackoverflow.com/questions/17663430/if-operator-works-properly-for-floating-point-types-why-cant-we-use-it-for-eq/ – tmyklebu Sep 18 '14 at 14:54

1 Answers1

0

You can use BigDecimal for this type of comparison:

BigDecimal a = new BigDecimal("5").subtract(new BigDecimal("4.9")); // == 0.1
BigDecimal b = new BigDecimal("0.1"); // == 0.1
System.out.println(a.compareTo(b)); // 0 - they are equal

Output

0
Mena
  • 47,782
  • 11
  • 87
  • 106