Working with float variables in javascript

Hi all,

I've been trying to use float variables in my code below:

class CodingNode{

var f1aList = new Array();
var f1b;
var activity : float = 0.0;
var choiceValue = -1;

function CodingNode(){
	Debug.Log("Coding node created");
	this.activity = 0.0;
	Debug.Log("Activity = " + activity);
	choiceValue = 1/2;
	Debug.Log("Choice = " + choiceValue);


However the Debug messages show "0" for both the variable activity and choiceValue, when they should be showing "0.0" for activity and "0.5" for choiceValue. Any help would be greatly appreciated.


When you write "1/2" you are dividing an integer by an integer. Many languages, including C and Unity JavaScript, assume that you want integer division; the result is therefore truncated to an integer. The fact that it is then assigned to a variable that was declared as a float makes no difference.

To get floating point division, either the numerator or denominator (or both) just needs to be a float.

Also note that Debug.Log does not put a trailing decimal ".0" on whole decimals. So you can't necessarily tell from the output whether a given round number is a float or not.

put 1.0/2.0 and then you will see the correct results. in javascript the variables are dynamic and their type can be changed. the problem is you are deviding 2 integer numbers. in C# you can use f as suffix "1f" to say the number is a float but i don't know can you do this in javascript or not. i am sure that if you use 1.0 and 2.0 it will give you 0.5 but i don't know it's a double or float. the problem surely is about number literals and is not about variable type because they are dynamic in javascript. hope this helps