Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast Double to Integer in Java

Tags:

java

casting

Any way to cast java.lang.Double to java.lang.Integer?

It throws an exception

"java.lang.ClassCastException: java.lang.Double incompatible with java.lang.Integer"

like image 462
4lex1v Avatar asked Feb 01 '12 19:02

4lex1v


People also ask

Can you cast a double to an int Java?

Since double is bigger data type than int, you can simply downcast double to int in Java. double is 64-bit primitive value and when you cast it to a 32-bit integer, anything after the decimal point is lost.

Can you cast double in Java?

In Java when you cast you are changing the “shape” (or type) of the variable. The casting operators (int) and (double) are used right next to a number or variable to create a temporary value converted to a different data type. For example, (double) 1/3 will give a double result instead of an int one.

How do you round double to int?

round() Math. round() accepts a double value and converts it into the nearest long value by adding 0.5 to the value and truncating its decimal points. The long value can then be converted to an int using typecasting.

How can a double value be assigned to an integer variable?

#1) Typecasting In this way of conversion, double is typecast to int by assigning double value to an int variable. Here, Java primitive type double is bigger in size than data type int. Thus, this typecasting is called 'down-casting' as we are converting bigger data type values to the comparatively smaller data type.


1 Answers

You need to explicitly get the int value using method intValue() like this:

Double d = 5.25; Integer i = d.intValue(); // i becomes 5 

Or

double d = 5.25; int i = (int) d; 
like image 64
anubhava Avatar answered Oct 04 '22 20:10

anubhava