Is there an idiomatic way to round to the nearest multiple of a number, short of rounding both up and down and seeing which one is closest?
Assume only integers:
number multiple result
12 5 10
13 5 15
149 10 150
Add half of the multiple, then round down.
result = ((number + multiple/2) / multiple) * multiple;
or
result = number + multiple/2;
result -= result % multiple;
This rounds up if the number is exactly in the middle. You might need to tweak the calculation if you want different behaviour in that case. Also, beware overflow if number
might be near the top of the type's range.
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