0
class test{
public static void main(String... args){
    double d=5.637;
    System.out.println("double is:"+d);
    long a=(long)d;
    System.out.println("long is:"+a);
   }
}

The output of above code is long is : 5, which is as expected.

But when I ran the following code:

class test{
public static void main(String... args){
     double d=12345678901234567890.637;
     System.out.println("double is:"+d);
     long a=(long)d;
     System.out.println("long is:"+a);
  }
}

The output is not as expected. the the result is long is:9223372036854775807

I want to ask why does it happen when I take huge number in double.

Sudheesh Singanamalla
  • 2,283
  • 3
  • 19
  • 36
  • long form of this double crosses the maximum value allowable in long. – jack jay Feb 07 '17 at 07:21
  • When a `double` value exceeds the max value of `long`, the result of the [Narrowing Primitive Conversion (JLS §5.1.3)](https://docs.oracle.com/javase/specs/jls/se8/html/jls-5.html#jls-5.1.3) from `double` to `long` is `Long.MAX_VALUE`, i.e. `9223372036854775807`: *[When] floating-point number is converted to a `long`, [... and] the value [is] too large (a positive value of large magnitude or positive infinity), and the result [...] is the largest representable value of type `long`.* – Andreas Feb 07 '17 at 07:49

1 Answers1

1

for safest casting you should use Math.round(d) and max long size is 9,223,372,036,854,775,807 you are trying to assing bigger double value to long

edit: you can use BigInteger instead of Long

U X
  • 121
  • 1
  • 1
  • 6