[SOLVED] typecast float to int in javascript?

A forum search has lead me to think it’s not doable.

“as” only works on reference types and Unity doesn’t dig

	var f1 : float = 3.14;
	var myVar : int = (int)f1;

or

	var f1 : float = 3.14;
	var myVar : int = int(f1);

If anyone knows a typecast method that work’s I’d appreciate a “how to”.

1 Like

Hello

On JS use parseInt(yourFloatHere)

so it will be something like this:

var f1 : float = 3.15;
var i1 : int = parseInt(f1);

if it doesnt work, try with ParseInt() cant remember well if its lower or upper case :stuck_out_tongue:

hope it helps ;)!!!

2 Likes

You dah man! Thanx.

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));

results in i1 = 3 and i2 = 4.

Thanx again for the info, you saved the day!

1 Like

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(…).

1 Like

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.

–Eric

1 Like