Question

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?

Was it helpful?

Solution

Math.Round(num / 3);

or

Math.Ceiling(num / 3);

or

Math.Truncate(num / 3);

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top