【问题标题】:How do I round up a number to the nearest 10 in python 3.4.0?如何在 python 3.4.0 中将一个数字四舍五入到最接近的 10?
【发布时间】:2016-03-04 06:13:57
【问题描述】:

因为“round”会将诸如24 down之类的数字四舍五入到20,所以当我需要将答案up四舍五入到30时。请帮帮我!我已经被困了很久了:(

【问题讨论】:

标签: numbers rounding


【解决方案1】:

导入数学

定义综述(x):

#rounding method
return int(math.ceil(x / 10.0)) * 10

【讨论】:

    【解决方案2】:

    此函数将正确地向上和向下舍入:

    import math
    
    def roundup(x, n=10):
        res = math.ceil(x/n)*n
        if (x%n < n/2)and (x%n>0):
            res-=n
        return res
    
    num = [5,9,11,15]
    r_num = [roundup(n) for n in num]
    
    print(r_num)
    # [10, 10, 10, 20]
    
    

    【讨论】:

    • OP 希望 24 将 向上 舍入到 30。
    • 这个函数似乎也将 20 舍入到 10。
    • “到最接近的 10”是不明确的。另外,更正了代码。
    • 当然,但问题主体很清楚:OP 非常明确地希望将 24 舍入为 30。
    • 啊!对我不小心。 (我应该删除我的答案吗?)
    猜你喜欢
    • 1970-01-01
    • 2017-07-26
    • 2013-08-31
    • 2017-05-03
    • 2011-03-21
    • 1970-01-01
    • 1970-01-01
    • 2012-01-25
    相关资源
    最近更新 更多