Can you help me to round like the following?
10 -> 12
21 -> 22
22 -> 22
23 -> 32
34 -> 42
I tried answers from below, but all of them are rounding to next multiplier of a number:
Can you help me to round like the following?
10 -> 12
21 -> 22
22 -> 22
23 -> 32
34 -> 42
I tried answers from below, but all of them are rounding to next multiplier of a number:
You can compare the number mod 10 to 2; if less than or equal to 2, add 2 - num % 10 else add 12 - num % 10 to get to the nearest higher (or equal) number ending in 2:
def raise_to_two(num):
if num % 10 <= 2:
return num + 2 - num % 10
return num + 12 - num % 10
print(raise_to_two(10))
print(raise_to_two(21))
print(raise_to_two(22))
print(raise_to_two(23))
print(raise_to_two(34))
Output:
12
22
22
32
42
Note (thanks to @MarkDickinson for pointing this out) that because the python modulo operator always returns a positive number if the second argument (to the right of % is positive), you can simplify the above to
def raise_to_two(num):
return num + (2 - num) % 10
The output remains the same
num + (2 - num) % 10import math
x = [10, 21, 22, 23, 34]
for n in x:
print((math.ceil((n-2)/10)*10)+2)
outputs:
12
22
22
32
42
math.ceil(...) * 10 are unnecessary.out = math.ceil((n-2)/10)*10 + 2; print(out)