I have kind of weird question.
Here is my code:
var num:Int = 10;
num /= 3;
And I get the following error message:
Float should be Int
What is the best way to make it work?
num = Std.int(num/3); looks really excessive to me.
Haxe infers division results, whether it be a float or an integer, as a float. Most statically typed languages do this because there is no way to tell what the result will be. You can do an unsafe cast if you prefer:
num = cast (num / 3);
Using an unsafe cast here is a bad idea, since it’s… well, unsafe. It might work on static targets, but for instance on JS and Neko, the result of that code snippet will be
3.333 rather than the desired
3 (Try Haxe !).
Std.int() is the way to go. If you feel it’s too long, you could statically import it:
num = int(num / 3);
Or even use it as a static extension:
num = (num / 3).int();
Thanks for answers guys, looks like I’ll stay with