A general method to round a number to a multiple of another number, rounding away from zero.
For integer
int RoundNum(int num, int step)
{
if (num >= 0)
return ((num + (step / 2)) / step) * step;
else
return ((num - (step / 2)) / step) * step;
}
For float
float RoundNum(float num, float step)
{
if (num >= 0)
return floor((num + step / 2) / step) * step;
else
return ceil((num - step / 2) / step) * step;
}
I know some parts might seem counter-intuitive or not very optimized. I tried casting (num + step / 2) to an int, but this gave wrong results for negative floats ((int) -12.0000 = -11
and such). Anyways these are a few cases I tested:
- any number rounded to step 1 should be itself
- -3 rounded to step 2 = -4
- -2 rounded to step 2 = -2
- 3 rounded to step 2 = 4
- 2 rounded to step 2 = 2
- -2.3 rounded to step 0.2 = -2.4
- -2.4 rounded to step 0.2 = -2.4
- 2.3 rounded to step 0.2 = 2.4
- 2.4 rounded to step 0.2 = 2.4