Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Compare Two Numbers in Java? [duplicate]

Tags:

Possible Duplicate:
Comparing the values of two generic Numbers

I would like to compare two arbitrary instances of Number to find out which is greater. As you know, those may be Integers, Longs or Doubles but also BigIntegers or BigDecimals. So what to do?

  1. Number does not implement Comparable.
  2. Can't use doubleValue() as there might be a loss of precision from BigDecimals or BigIntegers.

Do I really have to go into instance-testing and casting? There must be some library that does this. But I've already checked Apache Commons and Guava with no luck.

Edit 1: Comments pointed this out: Comparing the values of two generic Numbers. It has a solution that converts everything to a BigDecimal using toString(). Is there really no better way to do this?

Edit 2: I just posted my own version as an answer to the other question. It should be more efficient and robust than the accepted answer.

like image 536
rolve Avatar asked Sep 24 '12 08:09

rolve


People also ask

How do you compare two numbers in Java?

To check two numbers for equality in Java, we can use the Equals() method as well as the == operator. Firstly, let us set Integers. Integer val1 = new Integer(5); Integer val2 = new Integer(5); Now, to check whether they are equal or not, let us use the == operator.

How do you find duplicates in two arrays in Java?

You should leverage a hashmap/hashset for a substantially faster O(n) solution: void findDupes(int[] a, int[] b) { HashSet<Integer> map = new HashSet<Integer>(); for (int i : a) map. add(i); for (int i : b) { if (map. contains(i)) // found duplicate! } }

Can we compare double and long in Java?

The main difference between long and double in Java is that long is a data type that stores 64 bit two's complement integer while double is a data type that stores double prevision 64 bit IEEE 754 floating point. In brief, long is an integral type whereas double is a floating point type.

Can you use == to compare ints in Java?

To compare integer values in Java, we can use either the equals() method or == (equals operator). Both are used to compare two values, but the == operator checks reference equality of two integer objects, whereas the equal() method checks the integer values only (primitive and non-primitive).


2 Answers

You can't compare two arbitrary instances of type Number, because this is a possibly endless operation. Imagine two irrational numbers, where the only difference is in the billion-th decimal. You would have to compare some billion decimals for this.

You need to convert your Number instances to BigDecimal, applying rounding as necessary, and then compare these both.

like image 184
SpaceTrucker Avatar answered Oct 23 '22 16:10

SpaceTrucker


Strictly speaking, Number can not be compared. You need first to define the semantics of the comparison. Since you mentioned its for library use, you probably want to only rely on what the Number API offers.

So its down to comparing the values of either longValue() or doubleValue(). I suggest an approach that compares using longValue() first, and if they turn out to be equal, compare the doubleValue() as well (this way you catch long overflows, but still maintain 64 bit long precision when the values are not floats):

public static int compare(Number n1, Number n2) {
    long l1 = n1.longValue();
    long l2 = n2.longValue();
    if (l1 != l2)
        return (l1 < l2 ? -1 : 1);
    return Double.compare(n1.doubleValue(), n2.doubleValue());
}

Everything else is a guessing game exceeding what the Number API offers. For standard use above code should work fairly well. And yes, if you pass it (for example) BigIntegers or BigDecimals that are outside of Doubles value range or have a differences only beyond 53 bits of mantissa precision, they are wrongly detected as being equal, but as far as the Number API is concerned this wrong result can be seen as the "correct" one.

like image 39
Durandal Avatar answered Oct 23 '22 16:10

Durandal