How to Compare Two Numbers in Java?(如何在 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.
这篇关于如何在 Java 中比较两个数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 Java 中比较两个数字?


- Jersey REST 客户端:发布多部分数据 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01