[英]Convert/Cast Double to int? (Object to primitive type)
How do I convert/cast a Double
object to an int
? 如何将
Double
对象转换/转换为int
?
Double d = new Double(12.34);
int i = 12 //is what I'm looking for
If I had a double
I would just use: 如果我有一个
double
我只会使用:
double z = 12.34;
int i = (int)z;
Note: I want it to truncate the Double
(so 12.9 becomes 12) because I know that d
actually was an integer that was converted to a Double. 注意:我希望它截断
Double
(因此12.9变为12),因为我知道d
实际上是一个转换为Double的整数。 Ie I want to call (int) on a Double
. 即我想在
Double
上调用(int)。
To perform this operation you need to call the intValue
method on the Double
object: 要执行此操作,您需要在
Double
对象上调用intValue
方法 :
int i = d.intValue();
This method performs a cast, into an int
value, on the double
value wrapped within the Double
object, d
. 此方法对包装在
Double
对象d
的double
值执行强制转换为int
值。
Note that it does not check for null
before attempting this. 请注意,尝试执行此操作之前不会检查是否为
null
。
If you want to use a cast you can use 如果您想使用演员表,可以使用
Double d = 12.34;
int i = (int) (double) d;
You can't cast from Double
to int
in one step. 您不能一步一步将
Double
为int
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.