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

Paweł Kowalski
  • 524
  • 3
  • 9
  • 1
    What have you tried so far? Please see: [Why is “Can someone help me?” not an actual question?](http://meta.stackoverflow.com/q/284236) – Brian McCutchon Jan 02 '21 at 23:02

4 Answers4

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

Nick
  • 138,499
  • 22
  • 57
  • 95
  • Just compare mod 2. If it is zero add 2, if it is one add 1. – Michael Hofmann Jan 02 '21 at 23:07
  • 1
    @MichaelHofmann it's not rounding to the next multiple of 2, it's rounding to the next higher number which ends in 2. – Nick Jan 02 '21 at 23:08
  • You could get rid of the branching here and just return `num + (2 - num) % 10` – Mark Dickinson Jan 03 '21 at 13: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. – Nick Jan 03 '21 at 22:01
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
couka
  • 1,361
  • 9
  • 16
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}")

armamut
  • 1,087
  • 6
  • 14
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
wjandrea
  • 28,235
  • 9
  • 60
  • 81
CesarCr300
  • 11
  • 1