Round to nearest multiple of a number

后端 未结 2 1377
逝去的感伤
逝去的感伤 2020-12-16 14:26

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 o

相关标签:
2条回答
  • 2020-12-16 14:33

    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.

    0 讨论(0)
  • 2020-12-16 14:33

    I've answered this before on Rounding off a number to the next nearest multiple of 5

    With using cmath::abs

    int rounded = n + abs((n % denom) - denom);
    

    You can change denom with any denomination you want

    0 讨论(0)
提交回复
热议问题