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"
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.
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.
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.
#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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With