1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > 在Java中将Double转换为Integer

在Java中将Double转换为Integer

时间:2019-12-18 13:23:14

相关推荐

在Java中将Double转换为Integer

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

Any way to castjava.lang.Doubletojava.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楼

参考:/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 = 9Double D = 9.5;int i = Integer.valueOf(D.intValue());//i = 9double 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 useintValue().实际上,最简单的方法是使用intValue()。However, this merely returns the integer part;但是,这只返回整数部分;it does not do any rounding.它没有做任何舍入。If you want the Integernearestto 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 thepitfalls and reasoningbehind it.我认为,如果不解决其背后的陷阱和推理,就无法理解其他答案。

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

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

Strategy:战略:

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

Convert theDoubleobject to a primitivedouble.将Double对象转换为原始double。(= "unboxing")(=“取消装箱”)Convert the primitivedoubleto a primitiveint.将基本double转换为基本int。(= "casting")(=“铸造”)Convert the primitiveintback to anIntegerobject.将原始int转换回Integer对象。(= "boxing")(=“拳击”)

In code:在代码中:

// starting pointDouble myDouble = Double.valueOf(10.0);// step 1: unboxingdouble dbl = myDouble.doubleValue();// step 2: castingint intgr = (int) dbl;// step 3: boxingInteger val = Integer.valueOf(intgr);

Actually there is a shortcut.实际上有一条捷径。You can unbox immediately from aDoublestraight to a primitiveint.您可以立即从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 isnot 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 aDouble.但是,与Double相比,整数的范围(最小/最大值)非常小。On top of that, doubles can also hold "special values", that integers cannot:最重要的是,双打也可以保持“特殊值”,整数不能:

1/0 = +infinity1/0 = +无穷大-1/0 = -infinity-1/0 = -infinity0/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) = 1andround(0.4) = 0).在财务应用程序中,您肯定希望使用半向上舍入(例如:round(0.5) = 1round(0.4) = 0)。

// null-safe and with better roundinglong 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; // worksInteger val2 = 10.0; // doesn't workDouble val3 = 10; // doesn't workDouble val4 = 10.0; // worksDouble 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; // worksDouble val8 = (Double) Integer.valueOf(10); // doesn't workInteger val9 = (Integer) 9; // pure nonsense

Prefer valueOf:首选valueOf:

Also, don't be tempted to usenew Integer()constructor (as some other answers propose).另外,不要试图使用new Integer()构造函数(正如其他一些答案所提出的那样)。ThevalueOf()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

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。