我需要对一个 float 进行四舍五入。例如 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, "向上")
这会打印出 4.0002
my_round(4.00018, 4, "down")
这会打印出 4.0001
我找不到对此的问题(为什么?)。我还错过了其他模块或功能吗?拥有一个具有基本(更改的)功能的大型图书馆会很棒。
编辑:我不谈论整数。
最佳答案
查看我在 this SO post 中的回答.您应该能够通过将 floor
替换为 round
来轻松地根据您的需要修改它。
如果有帮助,请告诉我!
编辑 只是感觉而已,所以想提出一个基于代码的解决方案
import math
def round2precision(val, precision: int = 0, which: str = ''):
assert precision >= 0
val *= 10 ** precision
round_callback = round
if which.lower() == 'up':
round_callback = math.ceil
if which.lower() == 'down':
round_callback = math.floor
return '{1:.{0}f}'.format(precision, round_callback(val) / 10 ** precision)
quantity = 0.00725562
print(quantity)
print(round2precision(quantity, 6, 'up'))
print(round2precision(quantity, 6, 'down'))
产生
0.00725562
0.007256
0.007255
关于Python3如何按一定精度向上(向下)舍入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51906323/