Python中如何四舍五入到下一个以2结尾的整数?

How to round up to the next integer ending with 2 in Python?

你能帮我像下面这样四舍五入吗?

10 -> 12
21 -> 22
22 -> 22
23 -> 32
34 -> 42

我尝试了下面的答案,但所有答案都四舍五入到下一个数字乘数:

Round to 5 (or other number) in Python

Python round up integer to next hundred

你可以比较数字mod 10比2;如果小于或等于 2,则添加 2 - num % 10 否则添加 12 - num % 10 以获得最近的以 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))

输出:

12
22
22
32
42

注意(感谢@MarkDickinson 指出这一点)因为 python modulo 运算符总是 returns 如果第二个参数(在 %为正),可以将上面的简化为

def raise_to_two(num):
    return num + (2 - num) % 10

输出保持不变

这也应该有效。

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

这是代码:

 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
import math
x = [10, 21, 22, 23, 34]

for n in x:
    print((math.ceil((n-2)/10)*10)+2)

输出:

12
22
22
32
42