Last active
September 15, 2021 05:38
-
-
Save OR13/20bc2044e01d512a51d0 to your computer and use it in GitHub Desktop.
Round N to nearest multiple of M
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- | 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# edited with credit to https://gist.github.com/OR13/20bc2044e01d512a51d0#gistcomment-3745258 | |
def round_to_nearest(n, m): | |
return (n + m - 1) // m * m |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 andround_to_nearest(20.48, 0.05)
should be 20.50 ?