Anuj Sharma
Anuj Sharma

Reputation: 15

How does the Below Java Type casting works?

How does the output turn out to be '1'?

long number = 499_999_999_000_000_001L;    
double converted = (double) number;
System.out.println(number - (long) converted);

Upvotes: 1

Views: 83

Answers (2)

sgrpwr
sgrpwr

Reputation: 461

TLDR: It's because of overflow bits

If you check java documentation Double.MAX_VALUE. You will observe that max double integer value supported by java is 2^53 ≅ 10^16 but your value becomes (4.99999999 * 10^17) after typecasting which is outside the range of double so because of overflow it is rounded. For better understanding run this code.

public class Main
{
    public static void main(String[] args) {
        long longNumber = 499_999_999_000_000_001L;
        double doubleNumber = (double) longNumber;
        long longConverted = (long)doubleNumber;
        System.out.println(longNumber+" "+doubleNumber+" "+longConverted);
    }
}

Its output will be:

499999999000000001 4.99999999E17 499999999000000000

Upvotes: 3

Abra
Abra

Reputation: 20914

All you need to do is a little "debugging".
Try running this code...

long number = 499_999_999_000_000_001L;
System.out.println(number);
double converted = (double) number;
System.out.println(converted);
System.out.println((long) converted);
System.out.println(number - (long) converted);

This is what it displays...

499999999000000001
4.99999999E17
499999999000000000
1

Do you want to know why the conversion back to long from double drops the 1?
If you do then I refer you to the java specifications.

EDIT

To be precise, refer to section Widening Primitive Conversion

A widening primitive conversion from ... long to double, may result in loss of precision - that is, the result may lose some of the least significant bits of the value. In this case, the resulting floating-point value will be a correctly rounded version of the integer value, using IEEE 754 round-to-nearest mode (§4.2.4).

Upvotes: 2

Related Questions