1

Apologies if this was asked before, I can't seem to find an answer in regards to arbitrary multiples.

I would like a function that rounds a number by multiples. E.g, 17.4 would be rounded in multiples of 5 to 15, where 17.6 would result in 20.

This is what I came up with:

def value_2_rounded_multiple(value, multiple=1):
    return round(value / multiple)  *  multiple

Is this reasonable, or is there a better approach?

This is some auxiliary code for testing:

multiple = 5
shift = -0.1
val_ = (multiple / 2) + shift + 3 * multiple
print("{} becomes {}".format(val_, value_2_rounded_multiple(val_, multiple=multiple)))
elzurdo
  • 579
  • 1
  • 4
  • 14
  • 3
    Your solution looks perfectly fine to me (the function name could be better though). Also, [Code Review Stack Exchange](https://codereview.stackexchange.com) is probably a more appropriate place for this question. – lakshayg Nov 01 '18 at 18:17
  • Possible duplicate of [Python round up integer to next hundred](https://stackoverflow.com/questions/8866046/python-round-up-integer-to-next-hundred) – Sheldore Nov 01 '18 at 18:18
  • 1
    Yes, your function is a perfectly reasonable and understandable way to do this. The name is misleading, as this is *not* a modulus operation. Rather, you're rounding to the nearest `N` for values of `N` that are not the customary powers of 10. – Prune Nov 01 '18 at 18:19
  • Check the above duplicate link. One of the answers is general – Sheldore Nov 01 '18 at 18:19
  • thank you @Prune for your comments, I changed the naming and text to refer to "multiple" – elzurdo Nov 01 '18 at 18:26
  • 1
    @Bazingaa thank you for the reference, but they all discuss rounding up. I want more flexibility than that (I want to round down, too). – elzurdo Nov 01 '18 at 18:27
  • @LakshayGarg , thanks for your kind words and reference to Code Review, I haven't used them in the past, but will in the future. – elzurdo Nov 01 '18 at 18:28

0 Answers0