I have come to a point in my game where I have to implement a feature which divides a number by 3 and makes it a whole integer. i.e. not 3.5 or 2.6 etc....
It was to be a whole number, like 3, or 5.
Does anyone know how I can do this?
Math.Round(num / 3);
or
Math.Ceiling(num / 3);
or
Math.Truncate(num / 3);
Divide by three and round up can be done with the math functions:
int xyzzy = Math.Ceiling (plugh / 3);
or, if the input is an integer, with no functions at all:
int xyzzy = (plugh + 2) / 3;
This can also be done in a more generic way, "divide by n
, rounding up":
int xyzzy = (plugh + n - 1) / n;
The Ceiling
function is for explicitly rounding up (towards positive infinity). There are many other variations of rounding (floor, truncate, round to even, round away from zero and so on), which can be found in this answer.
Found this which says that if you take the number to divide, add two, and divide by three you would get the correct answer. For example, 7/3 = 2.3, but (7+2)/3 = 3.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With