[英]Double value big enough returns an error in Java
I was basically playing with data types in order to learn java and here is what i am confused about. 我基本上是为了学习Java而使用数据类型,这就是我很困惑的地方。
double douVar = 30000000000.323262342134353;
int intVar = (int)douVar; // casting
System.out.println(intVar);
Now converting the douVar
to string i overwrite the double
variable: 现在将douVar
转换为字符串,我将覆盖double
变量:
douVar = 345839052304598; // returns an error: Integer number too long
System.out.println(Double.toString(douVar));
complete error: 完全错误:
Error:(20, 18) java: integer number too large: 345839052304598
I'm using IntellijIDEA compiler. 我正在使用IntellijIDEA编译器。 I didnt try this over eclipse though but i assume the compiler would not be so different. 我没有在eclipse上尝试过,但是我认为编译器不会有太大的不同。 Does this mean that casting would result in modifying the original variable as well? 这是否意味着强制转换也会导致修改原始变量?
In Java, constant numbers without a decimal are ints by default. 在Java中,默认情况下,不带小数的常数为int。 There are 2 ways to change the constant definition to a double: 有两种将常量定义更改为双精度的方法:
d
or D
at the end. 在末尾添加d
或D
.0
at the end 在末尾添加.0
douVar = 345839052304598d;
douVar = 345839052304598.0;
Java interprets 345839052304598
as an integer. Java将345839052304598
解释为整数。
In Java an Integer is 4 bytes long and therefore has a value range from –2 147 483 648
to 2 147 483 647
. 在Java中,整数为4个字节长,因此其值范围为–2 147 483 648
至2 147 483 647
。 (your number is obviously not in that range) (您的电话号码显然不在该范围内)
To make Java treat the number as a double, you must write: 要使Java将数字视为双精度数,您必须编写:
double d = 345839052304598D;
/* or */
double d1 = 345839052304598.0;
(Same goes for a long
, you have to write L
instead of D
in that case) (相同的时间很long
,在这种情况下,您必须写L
而不是D
)
The literal 345839052304598 will be considered as an integer
by the compiler
, since this value is to large for an integer, a compile time error is thrown. 文字345839052304598将被compiler
视为integer
,因为此值对于整数而言太大,则会引发编译时错误。 Therefore you need to tell the compiler that the value you want to use is actually double value, that you can do the following way: 因此,您需要告诉编译器您要使用的值实际上是双精度值,您可以执行以下方式:
douVar =345839052304598D; // note D at the end which tells comipler that it is double
When you declare number as 345839052304598 compiler tries to read it as a 32 bit integer. 当您将数字声明为345839052304598时,编译器将尝试将其读取为32位整数。 But since this exceed the range of int compiler throws the error. 但是由于超出了int编译器的范围,因此会引发错误。 You can use d, D or L suffix or add decimal place like .0 to to handle this, 您可以使用d,D或L后缀,也可以添加.0等小数位来处理,
Just change douVar = 345839052304598;
只需更改douVar = 345839052304598;
to douVar = 345839052304598.00;
到douVar = 345839052304598.00;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.