我需要四舍五入一个浮点数。例如 4.00011 。内置函数round()总是在数字 > .5 时向上舍入,在 <= 5 时向下舍入。这非常好。当我想向上(向下)四舍五入时,我import math使用函数math.ceil()(math.floor())。缺点是没有精确的“设置” ceil()。floor()所以作为一个 R 程序员,我基本上只会写我自己的函数:
def my_round(x, precision = 0, which = "up"):
import math
x = x * 10 ** precision
if which == "up":
x = math.ceil(x)
elif which == "down":
x = math.floor(x)
x = x / (10 ** precision)
return(x)
my_round(4.00018, 4, "up")
这打印 4.0002
my_round(4.00018, 4, "down")
这打印 4.0001
我找不到这个问题(为什么?)。有没有我错过的其他模块或功能?拥有一个具有基本(更改)功能的大型库会很棒。
编辑:我不谈论整数。