Python中高于阈值的四舍五入

Python中高于阈值的四舍五入,python,rounding,Python,Rounding,有没有实现以下目标的库或快捷方式?如果这是一个愚蠢的问题,很抱歉,我对python库不太熟悉 如果小数点高于某个阈值,我想取整,而不是。5 例如,如果我的阈值为.2,则: input => output 1.2 => 2 1.3 => 2 1.19 => 1 2.21 => 3 2.1 => 2 谢谢导入数学 import math input = 1.19 threshold = 1.2 math.floor(input) if input < th

有没有实现以下目标的库或快捷方式?如果这是一个愚蠢的问题,很抱歉,我对python库不太熟悉

如果小数点高于某个阈值,我想取整,而不是。5

例如,如果我的阈值为.2,则:

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

导入数学
import math
input = 1.19
threshold = 1.2
math.floor(input) if input < threshold else math.ceil(input)

1
输入=1.19 阈值=1.2 如果输入<阈值,则数学地板(输入)否则数学天花板(输入) 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
阈值=0.2
如果输入<(数学地板(输入)+阈值),则数学地板(输入)否则数学天花板(输入)
1.
您可以尝试以下方法:

threshold = 0.2

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

仅适用于正数。

1.19应返回1是,抱歉,剩余。但是代码做了你想要的@owninggreendragsdude现在检查我们需要改变这样的条件,如果(input-math.floor(input))@jaswan我写的代码工作正常,无需更改任何条件。…@Capie我将
t
视为
threshold
,如果
t
是阈值,则前面的答案将不起作用,这就是我建议更改的原因