I need to round integers to be the nearest multiple of another integer. Examples for results in the case of multiples of 100:
- 36->0
- 99->100
- 123->100
- 164->200
and so on.
I came up with the following code, that works, but feels "dirty":
int RoundToMultiple(int toRound, int multiple)
{
return (toRound + (multiple / 2)) / multiple * multiple;
}
This counts on the truncating properties of integer division to make it work. Can I count on this code to be portable? Are there any compiler setups where this will fail to give me the desired result? If there are, how can I achieve the same results in a portable way?
If needed for a better answer, it can be assumed that multiples will be powers of 10 (including multiples of 1). Numbers can also be assumed to all be positive.