当 5 是第一个非十进制数字时,舍入函数无法正常工作

Round function does not work well when 5 is the first non-decimal digit

我需要将我的数字四舍五入到最接近的十位。我决定使用函数 round(num, -1)。 它适用于每个以 5 结尾的数字旁边的所有数字。当第一个非十进制数字为 5 时,我总是想将数字向上舍入。但是每次我插入 25,例如,它 returns 20 而不是 30。否则,当我插入 15 时,它会正常工作,它 returns 20。有人能帮我吗?我怎样才能获得这种行为? :(

代码:

z = float(15)
print(round(z,-1))
# >20
y = float(25)
print(round(y,-1))
# >20

round 函数的行为可能 work-around。

import math

some_value = 35

print(math.ceil(someValue / 10) * 10 if some_value % 5 == 0  else round(some_value, -1))

此代码检查值是否可以被 5 整除,如果是,则将值除以 10,向上取整值 (ceil),然后再次将其乘以 10 - 否则执行简单的旧圆函数:)

您也可以将其包装在一个函数中:-

def round_val(val):
  return math.ceil(val / 10) * 10 if val % 5 == 0 else round(val, -1)
# if two multiples are equally close, rounding is done toward the even choice.
# The decision to round towards even makes subsequent calculations more accurate.
z = float(15)
print(round(z, -1))  # 20 because the 10's digit 1 is odd 2 is the next even
# digit
y = float(25)  # 20 because the 10's digit 2 is even
print(round(y, -1))
# Assume rounding up always. Using the example numbers 15 and 25 rounding
# down would be 20 and 30.
print(f'Sum of rounding up={sum((20, 30))}')
print(f'Sum of actual numbers={sum((15, 25))}')
print(f'Sum of rounding toward even={sum((z, y))}')
print(f'Average of rounding up={sum((20, 30)) / 2}')
print(f'Average of actual numbers={sum((15, 25)) / 2}')
print(f'Average of rounding toward even={sum((z, y)) / 2}')


# If rounding up is desired it can be accomplished with a function:
def round_up_fives(number):
    if not number // 5:  # number is not evenly divisible by 5
        return round(number, -1)
    else:
        return number + 5


print(f'{round_up_fives(z)=}')
print(f'{round_up_fives(y)=}')

输出

20.0
20.0
Sum of rounding up=50
Sum of actual numbers=40
Sum of rounding toward even=40.0
Average of rounding up=25.0
Average of actual numbers=20.0
Average of rounding toward even=20.0
round_up_fives(z)=20.0
round_up_fives(y)=30.0