简体   繁体   English

转换/转换双精度为int? (对象到基本类型)

[英]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对象ddouble值执行强制转换为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. 您不能一步一步将Doubleint

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM