Reputation:
I am facing issues while converting from double to long:
double power = Math.pow(2, 63);
long powerInLong = (double) power;
The above code returns:
9223372036854775807
while it should return:
-9223372036854775808
I am confused why is this happening.
Thanks in advance!
Upvotes: 2
Views: 351
Reputation: 271735
You are doing a conversion from double
to long
, which is a narrowing primitive conversion.
This conversion is clearly specified in the JLS §5.1.3 (emphasis mine):
A narrowing conversion of a floating-point number to an integral type T takes two steps:
In the first step, the floating-point number is converted either to a long, if T is long, or to an int, if T is byte, short, char, or int, as follows:
If the floating-point number is NaN (§4.2.3), the result of the first step of the conversion is an int or long 0.
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 (§4.2.3). Then there are two cases:
a. If T is long, and this integer value can be represented as a long, then the result of the first step is the long value V.
b. Otherwise, if this integer value can be represented as an int, then the result of the first step is the int value V.
Otherwise, one of the following two cases must be true:
a. The value must be too small (a negative value of large magnitude or negative infinity), and the result of the first step is the smallest representable value of type int or long.
b. The value must be too large (a positive value of large magnitude or positive infinity), and the result of the first step is the largest representable value of type int or long.
Because 2^63 exceeds the range of long
(but not the range of double), converting it to a long will result in the largest long
. This can be demonstrated also by converting Math.pow(2, 64)
to long
, which results in the same long
.
Upvotes: 2