This is an embarrassing question but:
How do I cast an int to a float in javascript?
In C/C++, this would be:
int a = 10;
float b = (float)a;
For now I am using:
var a = 10;
var b = 20;
/… /
var c:float = a;
var d:float = b;
var e:float = c/d;
But I don’t want to create a new variable just to cast something.
More generally, how does one cast objects/primitives in javascript? I could not find a good resource on this anywhere.
Thanks,
Jon
Casting in UnityScript is done through as
so
a as float
for example.
though the cast in that direction should normally work implicitely too
I tried that earlier and got:
Assets/Height Map/DynamicallyMakePlanes.js(370,41): BCE0006: ‘int’ is a value type. The ‘as’ operator can only be used with reference types.
I think it doesn’t work since int is a primitive?
Eric5h5
September 3, 2010, 8:38pm
4
In Javascript it would be
var a = 10;
var b : float = a;
–Eric
heh I log in for a completely unrelated purpose and learn something useful (“as”). Thanks dreamora. (I really need to go update my JavaScript/UnityScript article, but I think someone else did a better one…)
Eric:
Maybe this is nitpicky, but say you have:
var a = 10;
var b = 20;
var c:float = a/b;
You would get c == 0.
Is the only way to get around this to do:
var a = 10;
var b = 20;
var af:float = a;
var bf:float = b;
var c:float = af/bf;
Eric5h5
September 4, 2010, 1:36am
7
var c : float = parseFloat(a) / b;
or
var c : float = (a+0.0) / b;
–Eric
Thanks! I appreciate the fix Eric.
for my project I have gotten this to work out pretty simply:
#pragma strict
var af =0.0;
var ai = 0;
function Update ()
{
ai=af;
}