Skip to content

Instantly share code, notes, and snippets.

@OR13
Last active September 15, 2021 05:38
Show Gist options
  • Save OR13/20bc2044e01d512a51d0 to your computer and use it in GitHub Desktop.
Save OR13/20bc2044e01d512a51d0 to your computer and use it in GitHub Desktop.
Round N to nearest multiple of M
-- | Ternary operator.
-- Usage: (i > 0) ? i $ 1
(?) :: Bool -> a -> a -> a
True ? x = const x
False ? _ = id
-- round n to nearest multiple of m
roundToNearestMultiple :: Int -> Int -> Int
roundToNearestMultiple n m = (m >= n) ? m $ (n `div` m + 1) * m
# edited with credit to https://gist.github.com/OR13/20bc2044e01d512a51d0#gistcomment-3745258
def round_to_nearest(n, m):
return (n + m - 1) // m * m
@mjpieters
Copy link

mjpieters commented May 17, 2021

I can't say anything about the haskell code, but the Python code here has a syntax error in it (missing parens) and is specific to Python 2 (presumably) as the / division operator gives you a floating point number, not on integer.

Next, it is wrong for numbers that are already multiples of m, e.g. round_to_nearest(24, 8) should return 24, not 32. The correct formula is (n + m - 1) // m * m.

Corrected code:

def round_to_nearest(n, m):
    return (n + m - 1) // m * m

There is no need to handle the n <= m case separately.

It would be much simpler to just use math.ceil() however:

from __future__ import division  # Python 2 only
import math

def round_to_nearest(n, m):
    return m * math.ceil(n / m)

@OR13
Copy link
Author

OR13 commented May 17, 2021

thanks! I can't say I even remember why I have this gist...

@mjpieters
Copy link

It comes up rather high on a Google search for 'python round up to the nearest multiple', so I wanted to make sure it wasn't going to trip people up. 😃

@sammykagiri
Copy link

sammykagiri commented Sep 15, 2021

This is a good one. What about the equivalent of MROUND function in excel in which case round_to_nearest(20.46, 0.05) should be 20.45 instead of 20.50 and round_to_nearest(20.48, 0.05) should be 20.50 ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment