如何四舍五入到十位 (python3)

How to round to tens (python3)

我正在尝试将数字四舍五入到最接近的十(而不是十分之一)。例如52 变成 50,29 变成 30,325 变成 330,等等。我该怎么做?

解释:没有正确的解决方法

新手变体

我们取数字即 123

第一步获取最后一位数字。

在python中,如果我们将它转​​换成一个字符串,然后取[-1],即

,我们就可以做到这一点
int(str(123)[-1]) #will return 3

然后我们实现大于5或者小于5的逻辑

def round_to_10(i):
    last_digit = int(str(i)[-1])  # it will give the last digit i.e 123 will return 3
    if last_digit >= 5:  # if 3 >= 5 sets round_up to True
        return i + (10 - last_digit)  # we add 10 to the number end subtract the extra

    return i - last_digit  # if the first condition never occurs we subtract the extra

另一种方法

我们可以用 % 得到剩余的值,即如果我们从数字中取出所有 10ns,我们会得到是否还有一些剩余值。我们可以使用 % 运算符

10%100 # returns 0因为没有剩余价值

10%123#returns3等

此解决方案也适用于负数。

def round_to_10(i):
    last_digit = i%10 
    if last_digit >= 5:
        return i + (10-last_digit)
    return i-last_digit
    In [7]: round_to_10(4)
    Out[7]: 0
    
    In [8]: round_to_10(5)
    Out[8]: 10
    
    In [9]: round_to_10(123)
    Out[9]: 120

试试这个: 它所做的是将数字转为字符串并获取最后一个字符(以找到最后一个数字),然后检查 lastDigit 是否小于 5。如果小于 5,则它从数字中减去 lastDigit,例如 24 -> 20。否则,它添加 (10 - lastDigit) 使其等于最接近的 10,例如 25 -> 30

def roundToTenth(num):
    num = round(num) # To get rid of small bugs
    # To get the last digit, we turn it to a string and take the last character
    lastDigit = int(str(num)[(len(str(num))-1)])
    diff = 10 - lastDigit
    if lastDigit < 5:
        return num - lastDigit
    else:
        return num + (10-lastDigit)

最简单的方法是使用 round()。通常人们认为此功能仅适用于小数点后的数字,但使用负数将完成您打算做的事情而无需重新创建轮子。

x = round(452.76543, -1)

>>> 450.0

如果那个小数点让您感到困扰,请在回合前面加上一个 int 语句 int(round(452.76543, -1))

现在,我知道您已经接受了答案,但考虑一下如果您有一个十进制数(比如 512.273)会发生什么。使用 ThunderHorn 的 round_to_10 代码你会得到:

round_to_10(512.273)

>>> 509.273

这是行不通的。它应该是 510,但前提是您没有输入中的十进制值。

但是通过使用内置函数,您不仅拥有更少的代码,而且更健壮 well-tested 代码可以在任何一种情况下工作。