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

>> CHECK OUT THE COURSE

## 1. Overview

Dealing with numerical data often requires precision handling. One common scenario arises when we need to check whether a double is, in fact, a mathematical integer.

In this tutorial, we’ll explore the various techniques available to perform this check, ensuring accuracy and flexibility in our numeric evaluations.

## 2. Introduction to the Problem

First, as we know, aÂ double is a floating-point data type that can represent fractional values and has a broader range than Java int or Integer. On the other hand, a mathematical integer is a whole number data type that cannot store fractional values.

A double can be considered as representing a mathematical integer when the value after the decimal point is negligible or non-existent. This implies that the double holds a whole number without any fractional component. For example, 42.0D is actually an integer (42). However, 42.42D isn’t.

In this tutorial, we’ll learn several approaches to checking whether a double is a mathematical integer.

## 3. The Special Double Values: NaN and Infinity

Before we dive into checking if a double is an integer, let’s first look at a few special double values: Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY, and Double.NaN.

Double.NaN means the value is “not a number”. Thus, it’s not an integer either.

On the other hand, both Double.POSITIVE_INFINITY and Double.NEGATIVE_INFINITYÂ isn’t a concrete number in the traditional sense. They represent infinity, a special value that indicates a result of a mathematical operation that exceeds the maximum representable finite value for a double-precision floating-point number. Therefore, these two infinity values aren’t integers either.

Further, the Double class provides the isNan() and isInfinite() methods to tell if a Double object is NaN or infinite.Â So, we can first perform these special values checks before we check if a double is an integer.

For simplicity, let’s create a method to execute this task so that it can be reused in our code examples:

``````boolean notNaNOrInfinity(double d) {
return !(Double.isNaN(d) || Double.isInfinite(d));
}``````

## 4. Casting the doubleÂ to int

To determine whether a double is an integer, the most straightforward idea is probably first casting the double to an intÂ and then compare the casted int to the original double.Â If their values are equal, the double is an integer.

Next, let’s implement and test this idea:

``````double d1 = 42.0D;
boolean d1IsInteger = notNaNOrInfinity(d1) && (int) d1 == d1;
assertTrue(d1IsInteger);

double d2 = 42.42D;
boolean d2IsInteger = notNaNOrInfinity(d2) && (int) d2 == d2;
assertFalse(d2IsInteger);``````

As the test shows, this approach does the job.

However, as we know, double’s range is wider than int‘s in Java. So, let’s write a test to check what happens if the doubleÂ exceeds the int range:

``````double d3 = 2.0D * Integer.MAX_VALUE;
boolean d3IsInteger = notNaNOrInfinity(d3) && (int) d3 == d3;
assertTrue(!d3IsInteger); // <-- fails if exceeding Integer's range``````

In this test, we assign 2.0D * Integer.MAX_VALUE to the double d3. Obviously, this value is a mathematical integer but out of Java’s integer range. So, it turns out that this approach won’t work if the given double is outside of the Java integer’s range.

Moving forward, let’s explore alternative solutions that address scenarios where doubles surpass the range of integers.

## 5. Using the Modulo Operator ‘%‘

We’ve mentioned that if a double is an integer, it doesn’t have a fractional part. Therefore, we can test if the double is divisible by 1. To do that, we can use the modulo operator:

``````double d1 = 42.0D;
boolean d1IsInteger = notNaNOrInfinity(d1) && (d1 % 1) == 0;
assertTrue(d1IsInteger);

double d2 = 42.42D;
boolean d2IsInteger = notNaNOrInfinity(d2) && (d2 % 1) == 0;
assertFalse(d2IsInteger);

double d3 = 2.0D * Integer.MAX_VALUE;
boolean d3IsInteger = notNaNOrInfinity(d3) && (d3 % 1) == 0;
assertTrue(d3IsInteger);``````

As the test shows, this approach works even if the double is out of the integer range.

## 6. Rounding the double

The standard Math class provided a series of rounding methods:

• ceil() – Examples: ceil(42.0001) = 43; ceil(42.999) = 43
• floor() – Examples: floor(42.0001) = 42; floor(42.9999) = 42
• round() – Examples: round(42.4) = 42; round(42.5) = 43
• rint() – Examples: rint(42.4) = 42; rint(42.5) = 43

We won’t go into details of Math rounding methods in the list. All these methods share a common characteristic: they round the provided double to a close mathematical integer.

If a double represents a mathematical integer, after passing it to any rounding method in the list above, the result must be equal to the input double, for example:

• ceil(42.0) = 42
• floor(42.0) = 42
• round(42.0) = 42
• rint(42.0) = 42

Therefore, we can use any rounding method to perform the check.

Next, let’s take the Math.floor()Â as an example to demonstrate how this is done:

``````double d1 = 42.0D;
boolean d1IsInteger = notNaNOrInfinity(d1) && Math.floor(d1) == d1;
assertTrue(d1IsInteger);

double d2 = 42.42D;
boolean d2IsInteger = notNaNOrInfinity(d2) && Math.floor(d2) == d2;
assertFalse(d2IsInteger);

double d3 = 2.0D * Integer.MAX_VALUE;
boolean d3IsInteger = notNaNOrInfinity(d3) && Math.floor(d3) == d3;
assertTrue(d3IsInteger);``````

As demonstrated by the test results, this solution remains effective even when the double exceeds the integer range.

Of course, if we want, we can replace the floor() method with ceil(), round(), or rint().

## 7. Using Guava

Guava is a widely used open-source library of common utilities. Guava’s DoubleMath class provides the isMathematicalInteger() method. The method name implies that it’s exactly the solution we are looking for.

To include Guava, we need to add its dependency to ourÂ pom.xml:

``````<dependency>
<artifactId>guava</artifactId>
<version>33.0.0-jre</version>
</dependency>``````

Next, let’s write a test to verify whether DoubleMath.isMathematicalInteger() works as expected:

``````double d1 = 42.0D;
boolean d1IsInteger = DoubleMath.isMathematicalInteger(d1);
assertTrue(d1IsInteger);

double d2 = 42.42D;
boolean d2IsInteger = DoubleMath.isMathematicalInteger(d2);
assertFalse(d2IsInteger);

double d3 = 2.0D * Integer.MAX_VALUE;
boolean d3IsInteger = DoubleMath.isMathematicalInteger(d3);
assertTrue(d3IsInteger);``````

As evidenced by the test results, the method consistently produces the expected result, no matter whether the input double falls within or outside the range of Java integers.

Sharp eyes might have noticed we didn’t call notNaNOrInfinity()Â in the test above for NaN and infinity check. This is because the DoubleMath.isMathematicalInteger() method handles NaN and infinity too:

``````boolean isInfinityInt = DoubleMath.isMathematicalInteger(Double.POSITIVE_INFINITY);
assertFalse(isInfinityInt);

boolean isNanInt = DoubleMath.isMathematicalInteger(Double.NaN);
assertFalse(isNanInt);``````

## 8. Conclusion

In this article, we first discussed what “a double represents a mathematical integer” means. Then, we’ve explored different ways to check whether a double indeed qualifies as a mathematical integer.

While the straightforward casting of a double to an int (i.e., theDouble == (int) theDouble) may seem intuitive, its limitation lies in its inability to handle cases where theDouble falls beyond the range of Java integers.

To address this limitation, we looked at moduli and rounding approaches, which can correctly handle doubles whose values extend beyond the integer range. Furthermore, we demonstrated the DoubleMath.isMathematicalInteger() method from Guava as an additional, robust solution to our problem.

As always, the complete source code for the examples is available over on GitHub.

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

>> CHECK OUT THE COURSE
1 Comment
Inline Feedbacks