1

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:

Round to 5 (or other number) in Python

Python round up integer to next hundred

1

4 Answers 4

4

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

Sign up to request clarification or add additional context in comments.

4 Comments

Just compare mod 2. If it is zero add 2, if it is one add 1.
@MichaelHofmann it's not rounding to the next multiple of 2, it's rounding to the next higher number which ends in 2.
You could get rid of the branching here and just return num + (2 - num) % 10
@MarkDickinson thanks for that - I should have tested it because I can never seem to remember which languages return negative results for modulo when one input is negative. I've updated the answer.
3
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

4 Comments

The parentheses around math.ceil(...) * 10 are unnecessary.
@BrianMcCutchon Yes, but improve readability in my opinion
@couka For best readability, you could use a separate variable and add spaces, like out = math.ceil((n-2)/10)*10 + 2; print(out)
Well, readability vs shortness can be a trade-off and that's where the optimum is for me.
2

this should also work.

arr = [10, 21, 22, 23, 34]
for a in arr:
    b = ((a-3) // 10) * 10 + 12
    print(f"{a} -> {b}")

Comments

1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.