In PHP I know it's like this but in Python I can't transform the function:
PHP:
function roundBy($a, $b = 5) {
return (int)($a / $b + 0.5) * $b;
}
Python (Bad):
def roundBy(a, b):
return int((a / b + 0.5) * b)
Input -> expected output:
30, 5 -> 30
31, 5 -> 30
32, 5 -> 30
33, 5 -> 35
34, 5 -> 35
Here are several solutions:
EDIT: For all 3 options, the result is the same:
I see the 3rd option less efficient, since the functions could be applied in some parallel processing with
map
the following way to different values more easily:You can round to multiples with the following function where
a
is the value andb
is the multiple to round to:Python - Function example 1:
Python - Function Example 2 (Better, More Optimized):
return: