Int vs. Float operations

Hi guys,

this seems like a really stupid question to have to be asking but Unity can't seem to manage to do a simple maths sum. (Its probably me and I'll kick myself for it afterwards I'm sure)

a code sample:

function Update () {
    var division = 3/4;
    print (division);
}

this simple piece of code in a much larger script is giving me a lot of hassle. For some reason Unity decides that the answer to 3/4 is 0?!

whereas in this example:

function Update () {
    var division = 3 * 0.25;
    print (division);
}

it works out the right answer. I need to use the equivalant to the first example as I am using variables instead of the simple numbers

Any help would be much appreciated. I'm guessing its just me having a dumb moment

thanks Scribe

You are getting the result of an integer division. You just need to make the divisor (the 4) a float value:

var division = 3/4.0;

var division : float = 3/4;

You may need to define the type as shown above. In your second example, you use a floating point value so Unity automatically defines it as a float. I believe that may be your problem.

The reason that your not getting the correct answer is because an "int" is defined as an integer (If you don't know what an integer is, its a whole number).

Edited at the request of Statement: (Whole numbers are numbers with no decimal part value. Ex: 2, 30012, 4239842. These are not whole numbers: 1.2, 1.4, 54.4 )

When you divide with integers, it rounds to the nearest whole number. In this case, its closer to 0, so it rounds down. Like numerous people have already said, adding ".0" would have converted it to a floating point decimal (float) which would have an integer plus the string of digits past the decimal.

Another way to get around this is to cast. For instance, you might be using values that are awkward if they aren't integers (health or experience are common variables that are best left as ints).

This is how you cast in javascript:

function Update () {
    var division = parseFloat(3)/parseFloat(4);
    print (division);
}

And this is how you cast in C# for you C# lurkers :P

void Update () {
    float division = (float)3/(float)4;
    print (division);
}

//better  using  like  this: 
#Pragma strict 
function Update () {
var division:float = 3/4;    
print (division);
}