I am a bit confused why I can input the same math, but get very different output to the console. The working solution is a bit annoying to say the least.
The longest value ever calculated is 0.0625. The actual math solution for all examples is 6.25.
For this specific test, here are my two numbers:
total = 40
T = 640
float percent = total / T * 100;
Debug.Log("Percent of Tiles: " + percent + "%");
Incorrect. Math Fail. Output to Console: “Percent of T: 0%”
float percent = total * 100 / T;
Debug.Log("Percent of T: " + percent + "%");
Rounded. Things like this happen in Unity’s Console, although still annoying but not entirely wrong if rounded to an int. Output to Console: “Percent of T: 6%”
If both total and T are integers, then this operation will occur with integer division. That is, 40/640 = 0.0625 - except that these decimals cannot be stored in an integer. So it will be truncated to 0, and then multiplied by 100. 0 * 100 is 0. Then, that 0 is going to get stored in the float value at the end.
Case 2 is similar: 40 * 100 = 4000 / 640 = 6.25 but again, integers cannot hold the .25 and it is truncated to 6 and stored into the floating value.
In your last case, you’re doing your multiplication and division using a floating point number instead of an integer, so you get the correct result without truncation.
I guess I assumed that since the variable is a float (“percent”), it would automatically do all the math with floats rather than integers. Is this exclusive to C#? I am surprised I’ve never come across this problem before. edit: Then again, I rarely use floats or doubles. Most of my games need nothing more than 8 bits
So if I understand correctly, casting all integers as floats would resolve this issue?
float percent = (float)total / (float)T * 100f;
If I only do 100f instead of ‘100’? (since both ‘total’ and ‘T’ are indeed int’s.) it will still do the wrong math, right? Makes sense so far.
Yes but it’s not really necessary. As long a 1 operand is cast to a float then it’ll evaluate a float expression.
Note I intentionally put the parenthesis around the (T * 100f) to ensure that is evaluated before the division (can’t remember the order of precedence so I just make it explicit).
It’s also unnecessary in your example since the 100f is already a float (the ‘f’). So you could also do:
float percent = total / ((float)T * 100);
or float percent = total / (T * (float)100);
or float percent = total / (T * 100f);
I always add a .0 to numbers not an int as a visual aid and to let the compiler know I ain’t flipping ints around. I really despise the adding an f in C#. You cannot just double-click to select the number and copy and paste into the Transform fields.
I use US to avoid alot of MicroSoft verbosity. I will write in C# for clients and for any Asset Store stuff I have in my pipeline I will write a C# version. Verbosity and having to select parts of a number or string via mouse affect my carpal tunnel flare-ups.