Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Introduction

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.

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

2. Using Type Casting

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.

3. Compared with a Tolerance

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.

4. Using Float.compare()

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

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.

5. Using Math.round()

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

@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.

6. Using Scanner

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:

@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.

7. Conclusion

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

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

Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
1 Comment
Oldest
Newest
Inline Feedbacks
View all comments
Comments are closed on this article!