Reputation: 339
I'm new to C#, and I can't work out why I'm getting the following error on these lines of code.
"error CS0266: Cannot implicitly convert type 'double' to 'float'. An explicit conversion exists (are you missing a cast?)"
float rightEdgeOfFormation = (float) transform.position.x + (width * 0.5);
float leftEdgeOfFormation = (float) transform.position.x - (width * 0.5);
I thought writing (float) was the cast?
Thanks so much!
Upvotes: 0
Views: 18724
Reputation: 61993
A type cast has the highest precedence of all other operations. Therefore, (float) transform.position.x
is evaluated before + (width * 0.5)
. However, (width * 0.5)
is a double
expression, because the constant 0.5
is a double
constant. (You should have used 0.5f
if you wanted it to be float
.) And when adding a float
and a double
, C# always "promotes" the float
to double
. So, the result of float + double
is a double
, which is then not assignable to a float
.
To fix it, either put the entire expression in parentheses before casting to float
, or make your 0.5
a float
constant by writing it as 0.5f
.
Upvotes: 5
Reputation: 869
Use the following
float rightEdgeOfFormation = Convert.ToSingle(transform.position.x + (width * 0.5));
float leftEdgeOfFormation = Convert.ToSingle(transform.position.x - (width * 0.5));
Upvotes: 0
Reputation: 2313
I think it's just your brackets. float rightEdgeOfFormation = (float) (transform.position.x + (width * 0.5));
Upvotes: 1
Reputation: 1646
float rightEdgeOfFormation = (float)transform.position.x + ((float)width * 0.5F);
float leftEdgeOfFormation = (float)transform.position.x - ((float)width * 0.5F);
See https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/float
Upvotes: 1
Reputation: 6773
Try :
float rightEdgeOfFormation = (float) (transform.position.x + (width * 0.5));
float leftEdgeOfFormation = (float) (transform.position.x - (width * 0.5));
you are just casting transform.position.x not the entire expression & something else in the expression is causing the calculation to be done as a double.
Upvotes: 3
Reputation: 1256
You're multiplying by 0.5, when you're using floats you need to put f
at their end.
This will work:
float rightEdgeOfFormation = transform.position.x + (width * 0.5f);
float leftEdgeOfFormation = transform.position.x - (width * 0.5f);
Upvotes: 4