- Home /
Why does this simple calculation not show decimals?
I'm trying to calculate the amount of pages my inventory has:
float pages = Mathf.CeilToInt(InventoryItemHolder.transform.childCount / itemsPerPage);
the childCount is 19, the itemsPerpage is 16. I logged these numbers in the console to make sure the mistake isn't in there.
So, pages should be 2 (19 / 16 = 1.1875, rounded to upper int), however is 1.
The same problem happens when I simplify:
float pages = InventoryItemHolder.transform.childCount / itemsPerPage;
Pages is still 1, instead of the expected 1.1875.
Why is this, and how can I solve it?
Answer by FailDev · Jan 12, 2018 at 03:49 PM
Is childcount and itemsperpage both int's? If yes, Try casting the calculation to float, i think the implicit cast to float is only made after the calculation is allready done, which would result in behaviour you are observing.
float pages =((float)InventoryItemHolder.transform.childCount / itemsPerPage);
Right, but you don't cast the calculation to float but one of the operands. As soon as one of the operands is a float the calculation will be done using floats and the result will be a float.
That makes sense, and seems to be the solution indeed. Thank you.