Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's wrong with casting 0.0 to double?

Tags:

c#

.net

casting

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.

alt text

like image 206
Jiew Meng Avatar asked Nov 06 '10 12:11

Jiew Meng


People also ask

How to cast double into long?

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.

Can we convert long to double?

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.

How to turn a double into a long Java?

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.


2 Answers

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.

like image 55
Konrad Rudolph Avatar answered Oct 21 '22 04:10

Konrad Rudolph


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); 
like image 43
Darin Dimitrov Avatar answered Oct 21 '22 04:10

Darin Dimitrov