开发者

Cast int to double then back to int in java

开发者 https://www.devze.com 2023-03-13 07:13 出处:网络
quick question. Would this always be true? int i = ...; double d = i; if (i == (int) d) ... Or I need to 开发者_Python百科do rounding to be sure?

quick question.

Would this always be true?

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

Or I need to 开发者_Python百科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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号