java - 比较Java中的数字

标签 java comparison numbers

在 Java 中,所有数字类型都从 java.lang.Number 扩展而来。有一个类似以下的方法是不是一个好主意:

public boolean areEqual(Number first, Number second) {
    if (first != null && second != null) {
        return first.equals(second);
    }
}

我担心双 2.00000 不等于 int 2 的情况。这些是否由内置的 equals 处理?如果没有,有没有办法在java中编写一个简单的数字比较函数? (apache commons等外部库都可以)

最佳答案

DoubleNEVER equalsInteger。此外,doubleDouble 不同。

Java 有原始类型和引用类型。 Java 中真正的数字类型不是从 Number 扩展而来的,因为它们是原语。

您可能需要考虑一个不混合类型的系统,因为这通常会给隐式/显式转换带来很多麻烦,可能/可能不会丢失信息等。

相关问题

关于 intInteger:

关于编号比较:

另见


关于混合类型的计算

混合类型计算是 Java Puzzlers 中至少 4 个谜题的主题。 .

以下是各种摘录:

it is generally best to avoid mixed-type computations [...] because they are inherently confusing [...] Nowhere is this more apparent than in conditional expressions. Mixed-type comparisons are always confusing because the system is forced to promote one operand to match the type of the other. The conversion is invisible and may not yield the results that you expect

Prescription: Avoid computations that mix integral and floating-point types. Prefer integral arithmetic to floating-point.

关于java - 比较Java中的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3214448/

相关文章:

java - 如何在 JasperReport 中将 svg 字节数组显示为图像?

Python:比较不冗余的列表项

c# - 从字符串中查找并提取所有数字

python - 比较 Sympy 因子结果为 false

javascript - 为什么这里输出0。变量 a = 7; a.构造函数();

java - 类似于 Soundex、Metaphone 等功能的数值转换算法

java - Android TensorFlow Lite 解释器 : How to fix "DataType error: cannot resolve DataType of java.lang.Float"

java - 如何调整 JPA 的大小以适应 Criteriaquery

java - 使用时间戳和偏移量进行时间处理

JavaScript Date.parse() 和空日期