2017-02-07 19 views
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); 
    } 
} 

上述代码的输出为long is : 5,这与预期的相同。在JAVA中从double到long的类型转换

但是,当我跑到下面的代码:

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

并不如预期的输出。其结果是long is:9223372036854775807

我想问为什么会发生这种情况,当我在双倍数量巨大的数字。

+0

长期形成的BigInteger的最长允许的最大值。 –

+0

当double值超过long的最大值时,[缩小基元转换(JLS第5.1.3节)]的结果(https://docs.oracle.com/javase/specs/jls/se8 /html/jls-5.html#jls-5.1.3)从'double'到'long'是'Long.MAX_VALUE',即'9223372036854775807':* [当]浮点数转换为'long'时, ,[...]和[值]太大(大幅值或正无穷大的正值),结果是“long”类型的最大可表示值。 – Andreas

回答

1

实现安全铸造你应该使用Math.round(d),最大长尺寸是9,223,372,036,854,775,807你想assing更大的双重价值长期

编辑:你可以用它代替这个双十字架长

相关问题