Check if a Float Value is Equivalent to an Integer Value in Java – 在 Java 中检查浮点值是否等同于整数值

最后修改: 2024年 1月 19日

中文/混合/英文(键盘快捷键:t)

1. Introduction

1.导言

The floating-point numbers are typically represented using Java’s float or double data type. However, precision imposes a limitation as they use binary representations of these values. When they are directly compared to integer values, the results might be unexpected.

浮点数通常使用 Java 的 floatdouble 数据类型表示。但是,由于这些数值使用二进制表示,因此精度受到限制。当它们直接与整数值进行比较时,结果可能会出乎意料。

In this tutorial, we’ll discuss various approaches to check if a float value is equivalent to an integer value in Java.

在本教程中,我们将讨论在 Java 中检查 float 值是否等同于 integer 值的各种方法。

2. Using Type Casting

2.使用类型铸造

One simple way is to use type casting to convert the float value into an integer and then compare it.

一种简单的方法是使用 类型转换 将浮点数值转换为整数,然后进行比较。

Here’s an example:

这里有一个例子:

float floatValue = 10.0f;

@Test
public void givenFloatAndIntValues_whenCastingToInt_thenCheckIfFloatValueIsEquivalentToIntegerValue() {
    int intValue = (int) floatValue;
    assertEquals(floatValue, intValue);
}

In this snippet, we initialize the floatValue with 10.0f. Then, we use type casting to convert it into an integer, and finally, we check if the floatValue is equivalent to the casted integer value intValue.

在此代码段中,我们将 floatValue 初始化为 10.0f。然后,我们使用类型转换将其转换为整数,最后检查 floatValue 是否等同于转换后的整数值 intValue

3. Compared with a Tolerance

3.与宽容度相比

Due to the floating-point precision limitations, using a tolerance when comparing float and integer values is often more suitable. This allows for variation due to the binary nature.

由于浮点精度的限制,在比较浮点和整数值时使用公差通常更为合适。这允许因二进制性质而产生的变化。

Let’s see the following code snippet:

让我们看看下面的代码片段:

@Test
public void givenFloatAndIntValues_whenUsingTolerance_thenCheckIfFloatValueIsEquivalentToIntegerValue() {
    int intValue = 10;
    float tolerance = 0.0001f;
    assertTrue(Math.abs(floatValue - intValue) <= tolerance);
}

Here, we initialize a float variable (tolerance) with 0.0001f. Then, we check if the absolute result of the difference between the floatValue and intValue variables is less than or equal to the tolerance value we set.

在这里,我们用 0.0001f 初始化一个浮点变量(公差)。然后,我们检查 floatValueintValue 变量之差的绝对值是否小于或等于我们设置的 tolerance 值。

4. Using Float.compare()

4.使用 Float.compare()

Java offers the Float.compare() method for accurate float comparison. This method treats NaN values and negative zero as reliable comparison mechanisms.

Java 提供了Float.compare()方法来进行精确的浮点比较。该方法将 NaN 值和负零值视为可靠的比较机制。

Here’s an example:

这里有一个例子:

@Test
public void givenFloatAndIntValues_whenUsingFloatCompare_thenCheckIfFloatValueIsEquivalentToIntegerValue() {
    int intValue = 10;
    assertEquals(Float.compare(floatValue, intValue), 0);
}

In this example, we utilize the Float.compare() method to check whether they are matched. The float.compare() method returns 0 if the two variables are equal, a negative number if the first variable is less than the second variable, and a positive number otherwise.

在本例中,我们使用 Float.compare() 方法来检查它们是否匹配。如果两个变量相等,float.compare() 方法返回 0;如果第一个变量小于第二个变量,则返回负数;否则返回正数。

5. Using Math.round()

5.使用 Math.round()

Another approach uses the Math.round() method. The built-in math method returns the closest long to the argument:

另一种方法是使用 Math.round() 方法。内置的数学方法会返回与参数最接近的长:

@Test
public void givenFloatAndIntValues_wheUsingRound_thenCheckIfFloatValueIsEquivalentToIntegerValue() {
    int intValue = 10;
    assertEquals(intValue, Math.round(floatValue));
}

Here, we directly round the float value using the Math.round() method and then check if the rounded value is equivalent to the integer value.

在这里,我们直接使用 Math.round() 方法对浮点数值进行舍入,然后检查舍入后的数值是否等同于整数数值。

6. Using Scanner

6.使用扫描仪</em

We can use the Scanner class to dynamically detect the type of user input, whether an integer or a float number. This approach enables interactive contributions, thereby making the program more flexible:

我们可以使用 Scanner 类动态检测用户输入的类型(整数还是浮点数)。

@Test
public void givenFloatAndIntValues_whenUsingScanner_thenCheckIfFloatValueIsEquivalentToIntegerValue() {
    String input = "10.0";
    Scanner sc = new Scanner(new ByteArrayInputStream(input.getBytes()));

    float actualFloatValue;
    if (sc.hasNextInt()) {
        int intValue = sc.nextInt();
        actualFloatValue = intValue;
    } else if (sc.hasNextFloat()) {
        actualFloatValue = sc.nextFloat();
    } else {
        actualFloatValue = Float.NaN;
    }

    sc.close();

    assertEquals(floatValue, actualFloatValue);
}

Here, we simulate user input as a string. The Scanner is then used to dynamically detect whether the input is an integer or a float, and the result is compared with the original float value.

在这里,我们将用户输入模拟为字符串。然后使用 Scanner 动态检测输入是整数还是浮点数,并将结果与原始浮点数值进行比较。

7. Conclusion

7.结论

In conclusion, we take a good overview of ways to verify if a float value equals an integer in Java.

最后,我们对 Java 中验证浮点数值是否等于整数的方法做了一个很好的概述。

As usual, the accompanying source code can be found over on GitHub.

与往常一样,您可以在 GitHub 上找到随附的源代码