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
@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