在Java中将Double转换为Integer

本文探讨了在Java中如何将Double转换为Integer,包括直接转换策略、自动装箱和拆箱、陷阱以及舍入策略。建议使用Double的valueOf方法进行转换,以利用缓存并避免异常。
摘要由CSDN通过智能技术生成

本文翻译自:Cast Double to Integer in Java

Any way to cast java.lang.Double to java.lang.Integer ? 有什么方法可以将java.lang.Doublejava.lang.Integer吗?

It throws an exception 它引发了一个例外

"java.lang.ClassCastException: java.lang.Double incompatible with java.lang.Integer" “java.lang.ClassCastException:java.lang.Double与java.lang.Integer不兼容”


#1楼

参考:https://stackoom.com/question/cBva/在Java中将Double转换为Integer


#2楼

double a = 13.34;
int b = (int) a;

System.out.println(b); //prints 13

#3楼

I see three possibilities. 我看到三种可能性。 The first two cut off the digits, the last one rounds to the nearest Integer. 前两个截断数字,最后一个截止到最接近的整数。

double d = 9.5;
int i = (int)d;
//i = 9

Double D = 9.5;
int i = Integer.valueOf(D.intValue());
//i = 9

double d = 9.5;
Long L = Math.round(d);
int i = Integer.valueOf(L.intValue());
//i = 10

#4楼

Double d = 100.00;
Integer i = d.intValue();

One should also add that it works with autoboxing. 还应该补充一点,它适用于自动装箱。

Otherwise, you get an int (primitive) and then can get an Integer from there: 否则,你得到一个int(原始),然后从那里得到一个Integer:

Integer i = new Integer(d.intValue());

#5楼

Indeed, the simplest way is to use intValue() . 实际上,最简单的方法是使用intValue() However, this merely returns the integer part; 但是,这只返回整数部分; it does not do any rounding. 它没有做任何舍入。 If you want the Integer nearest to the Double value, you'll need to do this: 如果你想要最接近 Double值的Integer,你需要这样做:

Integer integer = Integer.valueOf((int) Math.round(myDouble)));

And don't forget the null case: 并且不要忘记空案例:

Integer integer = myDouble == null ? null : Integer.valueOf((int) Math.round(myDouble)));

Math.round() handles odd duck cases, like infinity and NaN, with relative grace. Math.round()处理奇怪的鸭子情况,如无穷大和NaN,具有相对宽限度。


#6楼

I think it's impossible to understand the other answers without covering the pitfalls and reasoning behind it. 我认为,如果不解决其背后的陷阱和推理 ,就无法理解其他答案。

You cannot directly cast an Integer to a Double object. 您不能直接将Integer转换为Double对象。 Also Double and Integer are immutable objects, so you cannot modify them in any way. DoubleInteger也是不可变对象,因此您无法以任何方式修改它们。

Each numeric class has a primitive alternative ( Double vs double , Integer vs int , ...). 每个数字都有一个原始替代( Double vs doubleInteger vs int ,...)。 Note that these primitives start with a lowercase character (eg int ). 请注意,这些基元以小写字符开头(例如int )。 That tells us that they aren't classes/objects. 这告诉我们它们不是类/对象。 Which also means that they don't have methods. 这也意味着他们没有方法。 By contrast, the classes (eg Integer ) act like boxes/wrappers around these primitives, which makes it possible to use them like objects. 相比之下,类(例如Integer )就像这些基元周围的盒子/包装器一样,这使得它们可以像对象一样使用它们。

Strategy: 战略:

To convert a Double to an Integer you would need to follow this strategy: 要将Double转换为Integer您需要遵循以下策略:

  1. Convert the Double object to a primitive double . Double对象转换为原始double (= "unboxing") (=“取消装箱”)
  2. Convert the primitive double to a primitive int . 将基本double转换为基本int (= "casting") (=“铸造”)
  3. Convert the primitive int back to an Integer object. 将原始int转换回Integer对象。 (= "boxing") (=“拳击”)

In code: 在代码中:

// starting point
Double myDouble = Double.valueOf(10.0);

// step 1: unboxing
double dbl = myDouble.doubleValue();

// step 2: casting
int intgr = (int) dbl;

// step 3: boxing
Integer val = Integer.valueOf(intgr);

Actually there is a shortcut. 实际上有一条捷径。 You can unbox immediately from a Double straight to a primitive int . 您可以立即从Double直接拆箱到原始int That way, you can skip step 2 entirely. 这样,您可以完全跳过第2步。

Double myDouble = Double.valueOf(10.0);
Integer val = Integer.valueOf(myDouble.intValue()); // the simple way

Pitfalls: 陷阱:

However, there are a lot of things that are not covered in the code above. 但是,上面的代码中没有涉及很多内容。 The code-above is not null-safe. 上面的代码不是空的安全。

Double myDouble = null;
Integer val = Integer.valueOf(myDouble.intValue()); // will throw a NullPointerException

// a null-safe solution:
Integer val = (myDouble == null)? null : Integer.valueOf(myDouble.intValue());

Now it works fine for most values. 现在它适用于大多数值。 However integers have a very small range (min/max value) compared to a Double . 但是,与Double相比,整数的范围(最小/最大值)非常小。 On top of that, doubles can also hold "special values", that integers cannot: 最重要的是,双打也可以保持“特殊值”,整数不能:

  • 1/0 = +infinity 1/0 = +无穷大
  • -1/0 = -infinity -1/0 = -infinity
  • 0/0 = undefined (NaN) 0/0 =未定义(NaN)

So, depending on the application, you may want to add some filtering to avoid nasty Exceptions. 因此,根据应用程序的不同,您可能需要添加一些过滤以避免令人讨厌的异常。

Then, the next shortcoming is the rounding strategy. 然后,下一个缺点是舍入策略。 By default Java will always round down. 默认情况下,Java将始终向下舍入。 Rounding down makes perfect sense in all programming languages. 四舍五入在所有编程语言中都非常有意义。 Basically Java is just throwing away some of the bytes. 基本上Java只是丢​​掉了一些字节。 In financial applications you will surely want to use half-up rounding (eg: round(0.5) = 1 and round(0.4) = 0 ). 在财务应用程序中,您肯定希望使用半向上舍入(例如: round(0.5) = 1round(0.4) = 0 )。

// null-safe and with better rounding
long rounded = (myDouble == null)? 0L: Math.round(myDouble.doubleValue());
Integer val = Integer.valueOf(rounded);

Auto-(un)boxing 自动(UN)拳击

You could be tempted to use auto-(un)boxing in this, but I wouldn't. 你可能想在这里使用自动(非)拳击 ,但我不会。 If you're already stuck now, then the next examples will not be that obvious neither. 如果你现在已经陷入困境,那么下一个例子也不会那么明显。 If you don't understand the inner workings of auto-(un)boxing then please don't use it. 如果您不了解自动(非)拳击的内部工作原因,请不要使用它。

Integer val1 = 10; // works
Integer val2 = 10.0; // doesn't work

Double val3 = 10; // doesn't work
Double val4 = 10.0; // works

Double val5 = null; 
double val6 = val5; // doesn't work (throws a NullPointerException)

I guess the following shouldn't be a surprise. 我想以下不应该是一个惊喜。 But if it is, then you may want to read some article about casting in Java. 但如果是,那么你可能想阅读一些关于Java中的转换的文章。

double val7 = (double) 10; // works
Double val8 = (Double) Integer.valueOf(10); // doesn't work
Integer val9 = (Integer) 9; // pure nonsense

Prefer valueOf: 首选valueOf:

Also, don't be tempted to use new Integer() constructor (as some other answers propose). 另外,不要试图使用new Integer()构造函数(正如其他一些答案所提出的那样)。 The valueOf() methods are better because they use caching. valueOf()方法更好,因为它们使用缓存。 It's a good habit to use these methods, because from time to time they will save you some memory. 使用这些方法是一个好习惯,因为它们会不时地为你节省一些记忆。

long rounded = (myDouble == null)? 0L: Math.round(myDouble.doubleValue());
Integer val = new Integer(rounded); // waste of memory
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值