I’m used to parseInt() taking a String argument, not any other data type. So I did try the rather circuitous:
var f1 : float = 3.14;
var fs : String = f1.ToString();
var i1 : int = parseInt(fs);
Thing is, ToString() doesn’t seem to work on floats, trying to access the fs var from the code above throws a NullReferenceException. ToString() does work on the int type. The following works fine:
var i1 : int = 3;
var is : String = i1.ToString();
var i2 : int = parseInt(is);
Of course that’s redundant; why go through the trouble if i1 and i2 are the same. :roll: But it illustrates the point.
Note that parseInt() truncates a float so in:
var f1 : float = 3.14;
var f2 : float = 3.99;
var i1 : int = parseInt(f1);
var i2 : int = parseInt(f2);
i1 and i2 both = 3. In the project I’m working on that doesn’t matter, but if rounding is required:
var f1 : float = 3.14;
var f2 : float = 3.99;
var i1 : int = parseInt(Mathf.Round(f1));
var i2 : int = parseInt(Mathf.Round(f2));
In Javascript all numbers are stored as floats. Internally there’s no such thing as an “int” as usually understood. (Also, Javascript is a “loosely typed” language, so it doesn’t have a concept of “typecasting” in any case.) In Javascript, what seems to the user to be an integer is really just a floating point number with nothing meaningful after the decimal point.
The easiest way to produce something that acts pretty much like an int [while avoiding the transition to a string and back again of parseInt()] is to use the “round” function, something like this:
Depending on what you’re doing, Math.floor(…) or Math.ceil(…) may be more appropriate than Math.round(…).
Wrong-o. You’re on a Unity forum, and Unity doesn’t use web Javascript. None of what you wrote is true when it comes to Unity. Namely: int certainly exists, it’s not loosely typed, there is typecasting, and there is no Math.round (Mathf.Round, rather). This is why “Javascript” is frequently referred to as Unityscript, since it’s a custom language and has many significant differences compared to Javascript. You’d be better off thinking of it as being like ActionScript3, though there are still a number of differences compared to that.