Enable int to double, then return to int in java

quick question.

Will it always be?

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

Or do I need to round to be sure?

if (i == Math.round(d)) ...
+5
source share
3 answers

Yes, all possible values intcan safely round to double.

You can check this 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 am not using a regular loop forbecause it will either skip Integer.MAX_VALUEor the loop indefinitely.

Please note that for int/ floator for long/ double!

this value is not
+7
source

, , Java Β§ 5.1.2 :

19 :

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

. , , float double, ; . [...]

( Β§ 5.1.3 , , double β†’ int, .)

+1

A solution to Joachim.

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

Find the smallest value that causes an error to convert 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
0
source

All Articles