Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Round to nearest multiple of a number

Tags:

c++

math

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
like image 228
Luchian Grigore Avatar asked Apr 10 '15 09:04

Luchian Grigore


1 Answers

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.

like image 67
Mike Seymour Avatar answered Sep 27 '22 20:09

Mike Seymour