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



你能帮我像下面这样取整吗?

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

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

Python 中四舍五入到5(或其他数字(

Python将整数四舍五入到下一个百

您可以将数字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模运算符总是返回正数,因此可以将以上内容简化为

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

输出保持相同的

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

这也应该有效。

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

相关内容

最新更新