Search code examples
javatype-conversionprimitive

Cast int to double then back to int in java


quick question.

Would this always be true?

int i = ...;
double d = i;
if (i == (int) d) ...

Or I need to do rounding to be sure?

if (i == Math.round(d)) ...

Solution

  • Yes, all possible int values can round-trip to a double safely.

    You can verify it with this code:

        for (int i = Integer.MIN_VALUE; ; i++) {
            double d = i;
            if (i != (int) d) {
                throw new IllegalStateException("i can't be converted to double and back: " + i);
            }
            if (i == Integer.MAX_VALUE) {
                break;
            }
        }
    

    Note that I'm not using a normal for loop, because it would either skip Integer.MAX_VALUE or loop indefinitely.

    Note that the same is not true for int/float or for long/double!