- Home /
I'm wondering with if function working
Hi! I have question with if function, about is condition if I have 2 variable var A: float; var B:int;
and I make if(A>B) or if(B>A) if this function work? if if-function can compare with 2 different type of variable(int-float)
Answer by Polantaris · Jan 13, 2014 at 04:15 AM
You can do it two ways:
1)You can turn the float into an int using a cast. This is less accurate, but if you only care about the whole values in the float then the automatic truncation caused by the cast is fine.
2)You can turn the int into a float using a cast. This is the more accurate version, however my knowledge of floats means that (float)2 might actually end up something like 2.0000000002, and could potentially change your results depending on how many decimal places we are talking about.
In either case, you would do something like this:
1) if((int)(A) > B)
2) if((float)(B) > A)
Basically, by placing the primitive type in the front of the variable name, it says, "Treat this like (type) for now." You can do int division/multiplication the same way. For example, (int)(double a / double b). This would truncate (remove) the decimal places of the result, so if a = 1 and b = 3, the end result would be 0, because 1 / 3 = 0.33(repeating), and the .3333 is truncated resulting in 0. There is no rounding in truncation, so even if it was 0.99999999(repeating), the (int) cast of that would still be 0.
Your answer
![](https://koobas.hobune.stream/wayback/20220613130233im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Why can't won't my if then statements work? 1 Answer
Using if/else statements in GUI 1 Answer
Variable changes to a negative number somehow 1 Answer
script help needed 1 Answer