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
import 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
this should also work.
arr = [10, 21, 22, 23, 34]
for a in arr:
b = ((a-3) // 10) * 10 + 12
print(f"{a} -> {b}")
This is the code:
def round_by_two(number):
unitOfDecena = number // 10
residual = number % 10
if residual == 2:
requiredNumber = number
elif residual > 2:
requiredNumber = (unitOfDecena + 1)*10 + 2
else:
requiredNumber = unitOfDecena*10 + 2
return requiredNumber