I have InvalidCastException
when I try to cast 0.0 to double, why is that so? It's fine when I do (float)value
instead.
Let's check a straightforward way to cast the double to long using the cast operator: Assert. assertEquals(9999, (long) 9999.999); Applying the (long) cast operator on a double value 9999.999 results in 9999.
Convert long to double Using the doubleValue() Method in Java. If you have a long object, you can simply use the doubleValue() method of the Long class to get a double type value. This method does not take any argument but returns a double after converting a long value. See the example below.
round() method. Math. round() accepts a double value and converts it into the nearest long value by adding 0.5 and removing its decimal points.
In general, when you put a value type into an object
(called boxing) you need to unbox it to the exact same value type. You cannot do a conversion to another type instead. This is what happens here.
If you really want to convert the object, you first need to unbox it. Say your original value was a float
before you boxed it in an object
:
double d = (double) (float) value;
Or use the method proposed by others, which uses Convert
. This has the advantage that the original type doesn’t have to be known.
That's normal. If the object type is float
you cannot cast it to double
because they are not of the same type:
object o = 1.0f; double d = (double)o; // will throw an exception
You need to convert it:
double d = Convert.ToDouble(o);
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