How to Compare Two Numbers in Java? [duplicate]

断了今生、忘了曾经 提交于 2019-11-28 10:46:06

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!