Question

I'm a beginning programmer and I need a method that returns whether or not a double is an integer. The problem occurs when the number is too big for an int to hold.

Here's what I have:

private static boolean isInteger(double n){
    int ni = (int) n;
    double nd = (double) ni;
    if (nd==n)
        return true;
    return false;
}

Say I put in like 143215890634.0. It will return false because the int can't store that many digits.

How can I allow the int(or another class) to store more digits or is there a better way to determine if a double is an int without comparing like this?

Thanks in advance!

Was it helpful?

Solution

Well long holds more digits than int. By the time you get outside the range of long, all double values are integers (and separated by more than 1). So you could use something like:

private static boolean isInteger(double n) {
    if (n > (double) Long.MAX_VALUE ||  n < (double) Long.MIN_VALUE) {
        return true;
    }
    long asLong = (long) n;
    return n == (double) asLong;
}

There are alternative approaches which would determine the bitwise representation, and check the exponent - but they'd be more complicated, at least to understand.

Note that checking for exact values in binary floating point is usually a bad idea. You might instead want to check how close the double to the nearest integer, and have some sort of tolerance.

OTHER TIPS

try

boolean isInteger(double d) {
    return d % 1 == 0;
}

Compare it to Integer.MAX_VALUE. If it is smaller - it will fit into integer assuming it has no fraction.

To store lager numbers you would have to use long instead. As for the comparison, you could maybe do num == Math.round(num) instead.

I suppose, this would work even better than Math.round(), since it avoids type promotion:

    double d1 = 143215890634.0, d2 = 143215890634.001;
    System.out.println(d1 == Math.floor(d1));
    System.out.println(d2 == Math.floor(d2));

This works, if with "integer" you don't mean actual type "int", but a "number without position after decimal point".

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top