Reputation: 11279
Will a double equal to an integer always cast to that integer (assuming the double is not one that causes an overflow). Example: Math.ceil() will return a double that is equal to an integer. Assuming no overflow, will it always cast to the same integer that it is supposedly equal to?
If not, how can I round up a double
to an int
or long
?
Upvotes: 13
Views: 3216
Reputation: 4703
Yes, it will convert exactly. This is described in Section 5.1.3 of the JLS, which mentions
Otherwise, if the floating-point number is not an infinity, the floating-point value is rounded to an integer value V, rounding toward zero using IEEE 754 round-toward-zero mode...
Since your double
exactly equals the int
, the "rounded" value is just the exact same value, but you can read the spec for details.
Upvotes: 6
Reputation: 4608
I believe so, but you might test it yourself:
public static void main(String... args) throws Exception {
int interactions = Integer.MAX_VALUE;
int i = Integer.MIN_VALUE;
double d = Integer.MIN_VALUE;
long init = System.currentTimeMillis();
for (; i < interactions; i++, d++)
if (!(i == (int) Math.ceil(d)))
throw new Exception("something went wrong with i=" + i + " and d=" + d + ", Math.ceil(d)="+Math.ceil(d));
System.out.println("Finished in: "+(System.currentTimeMillis() - init)+"ms");
}
Upvotes: 1
Reputation: 328735
Empirically, the answer seems to be yes - note that it also works with i2 = (int) d;
.
public static void main(String[] args) {
for (int i = Integer.MIN_VALUE + 1; i < Integer.MAX_VALUE; i++) {
double d = i;
int i2 = (int) Math.ceil(d);
if (i != i2) {
System.out.println("i=" + i + " and i2=" + i2); //Never executed
}
}
}
Upvotes: 1
Reputation: 180997
Since Java types are fixed and Java doubles have a 52 bit mantissa, they can (with ease) represent a 32-bit Java int without rounding.
Upvotes: 9
Reputation: 533680
All possible int
values can be represented by a double without error. The simplest way to round up is to use Math.ceil() e.g.
double d =
long l = (long) Math.ceil(d); // note: could overflow.
Upvotes: 1