有什么库或快捷方式可以实现以下目标吗?很抱歉,如果这是一个愚蠢的问题,对python库不太熟悉。
如果小数点高于某个阈值而不是0.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
使阈值动态:
import math
input = 1.19
threshold = 0.2
math.floor(input) if input < (math.floor(input) + threshold) else math.ceil(input)
1
你可以试试这个:
threshold = 0.2
def round_up(a):
if a - int(a) >= threshold:
return int(a) + 1
return int(a)
仅适用于正数。
我找到的最短答案,
import math
threshold = 0.2
n = 3.4
roundup = math.ceil(n-threshold)