如何在 Java 中比较两个数字?
可能重复:
比较两个通用数字的值
我想比较 的两个任意实例Number 找出哪个更大.如您所知,它们可能是整数、长整数或双精度数,也可能是大整数或大小数.那么该怎么办呢?
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?
- 编号未实现 Comparable.
- 不能使用
doubleValue()
,因为 BigDecimals 或 BigIntegers 可能会损失精度.
- Number does not implement Comparable.
- Can't use
doubleValue()
as there might be a loss of precision from BigDecimals or BigIntegers.
我真的需要进行实例测试和铸造吗?必须有一些图书馆可以做到这一点.但是我已经检查了 Apache Commons 和 Guava,但没有运气.
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.
编辑 1: 评论指出了这一点:比较两个通用数字的值.它有一个解决方案,可以使用 toString()
将所有内容转换为 BigDecimal.真的没有更好的方法吗?
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?
编辑 2:我刚刚发布了我自己的版本作为另一个问题的答案.它应该比公认的答案更有效、更健壮.
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.
推荐答案
你不能比较 Number
类型的两个任意实例,因为这可能是一个无休止的操作.想象两个无理数,唯一的区别是十亿位小数.为此,您必须比较数十亿个小数.
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.
您需要将您的 Number
实例转换为 BigDecimal
,根据需要应用舍入,然后比较这两者.
You need to convert your Number
instances to BigDecimal
, applying rounding as necessary, and then compare these both.
相关文章