简体   繁体   中英

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

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 !

If you're on a slow computer or don't have time to run the loop to check for yourself, the relevant part of the Java Language Specification is here § 5.1.2 Widening Conversions :

The following 19 specific conversions on primitive types are called the widening primitive conversions:

  • byte to short, int, long, float, or double
  • short to int, long, float, or double
  • char to int, long, float, or double
  • int to long, float, or double
  • long to float or double
  • float to double

Widening primitive conversions do not lose information about the overall magnitude of a numeric value. Indeed, conversions widening from an integral type to another integral type and from float to double do not lose any information at all; the numeric value is preserved exactly . [...]

(The following section § 5.1.3 Narrowing Primitive Conversions ensures that the way back, double -> int, doesn't loose any information either.)

A variation on Joachim's solution.

int i=Integer.MIN_VALUE;
do {
    if(i != (int)(double) i) throw new AssertionError(i + " != (int)(double) "+i);
} while(i++ < Integer.MAX_VALUE);

To find the smallest value which causes an error for a conversion to float.

int i = 0;
do {
    if(i != (int)(float) i) throw new AssertionError(i + " != (int)(float) "+i);
} while(i++ < Integer.MAX_VALUE);

prints

java.lang.AssertionError: 16777217 != (int)(float) 16777217

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM