【问题标题】:Round up in Python above threshold value在 Python 中向上舍入高于阈值
【发布时间】:2020-11-16 13:01:08
【问题描述】:

是否有任何库或快捷方式来实现以下内容?对不起,如果这是一个愚蠢的问题,对python库不太熟悉。

如果小数点高于某个阈值而不是 0.5,我想四舍五入。

例如,如果我的阈值是 0.2,那么:

input => output
1.2 => 2
1.3 => 2
1.19 => 1
2.21 => 3
2.1 => 2

谢谢

【问题讨论】:

    标签: python rounding


    【解决方案1】:

    你可以试试这个:

    threshold = 0.2
    
    def round_up(a):
        if a - int(a) >= threshold:
            return int(a) + 1
        return int(a)
    

    仅适用于正数。

    【讨论】:

      【解决方案2】:
      import math
      input = 1.19
      threshold = 1.2
      math.floor(input) if input < threshold else math.ceil(input)
      
      1
      

      使阈值动态化:

      import math
      input = 1.19
      threshold = 0.2
      math.floor(input) if input < (math.floor(input) + threshold) else math.ceil(input)
      
      1
      

      【讨论】:

      • 1.19 应该返回 1
      • 是的,对不起,剩下的。但是代码可以满足您的要求。 @owninggreendragsdude 立即查看
      • 我们需要像这样改变条件,这将完成工作math.floor(input) if (input - math.floor(input)) &lt; t else math.ceil(input)
      • @jaswanth 我写的代码工作正常,无需更改任何条件.....
      • @Capie 我把t 当作threshold,如果t 是阈值,之前的答案将不起作用,这就是我建议更改的原因
      猜你喜欢
      • 2013-06-26
      • 1970-01-01
      • 2020-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多