如何在Java中比较两个数字? [英] How to Compare Two Numbers in Java?

查看:220
本文介绍了如何在Java中比较两个数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

比较两个通用数字的值

我想比较 Number 的两个任意实例,以了解这更大。你知道,这些可能是整数,长或双,但是BigIntegers或BigDecimals。那么该怎么办?

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. 号码未实现可比较

  2. 无法使用 doubleValue()因为BigDecimals或BigIntegers可能会损失精度。

  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.

编辑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:我刚发布我自己的版本作为对另一个问题的答案

推荐答案

你不能比较类型<$ c的两个任意实例$ c> 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中比较两个数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆