leora
leora

Reputation: 196499

In C#, why am i getting "can't cast double to float error"?

I have the following line of code:

    float top = shape.Y + (shape.Height / 2.0) - 4.5;

whic is failing with the error' Can't cast double to float. Shape.Y and shape.height are both type float.

What is causing this error and what is the best was to make sure top is a float (as i need to pass it into another function tha expects a float.

Upvotes: 1

Views: 2060

Answers (2)

Jeppe Stig Nielsen
Jeppe Stig Nielsen

Reputation: 61952

The cause is that your literals 2.0 and 4.5 are of type double.

Then in your expression

 shape.Y + (shape.Height / 2.0) - 4.5

the division seems to be between a float and a double. But there's an implicit conversion from float to double (the conversion in the other direction is not implicit), so Height is "widened" to a double. Then to add Y to this double, for the same reasons, Y too is widened to a double. Then the entire expression gets type double.

But you declare your top variable as a float, and the double expression cannot be converted to float implicitly.

Fuji gave the solution: If you write the literals as 2.0f (or just 2f) and 4.5f, then the addition, division and difference will be calculated as floats all the way, and no conversions are needed.

(Actually if you give the denominator as just 2, it will be converted from int to float implicitly, but as you can tell by now it is probably easier to see the intention if you include that f.)

Upvotes: 2

eandersson
eandersson

Reputation: 26352

Try to wrap your numbers with f, as normally 2.0 would represent a double number. You can read more about float here.

float top = shape.Y + (shape.Height / 2.0f) - 4.5f;

Upvotes: 10

Related Questions