Python 蟒蛇3如何以一定的精度向上(向下)取整

Python 蟒蛇3如何以一定的精度向上(向下)取整,python,python-3.x,Python,Python 3.x,我需要把一个浮点数四舍五入。例如4.00011。 内置函数round()总是在数字大于.5时向上取整,在查看我的答案时向下取整。通过将floor替换为round,您应该能够轻松地根据需要修改它 如果有帮助,请告诉我 编辑 我只是感觉到了,所以我想提出一个基于代码的解决方案 import math def round2precision(val, precision: int = 0, which: str = ''): assert precision >= 0 val

我需要把一个浮点数四舍五入。例如4.00011。 内置函数
round()
总是在数字大于.5时向上取整,在查看我的答案时向下取整。通过将
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

可能重复的nope。不幸的是没有。我不谈论整数。Julias round函数处理这个问题:
round(1.00018,RoundUp,digits=4)
round(1.00018,RoundDown,digits=4)
,所以julia lang标记可能不合适。谢谢!我只是根据我的需要编辑了你的函数,并提出了我的重写解决方案。太棒了!很高兴这有帮助,我只是添加了一个代码示例解决方案,因为我无法抗拒自己编写代码的冲动…:-P另外,如果您能选择我的解决方案作为帮助,我将很高兴;谢谢砰!我现在更喜欢你的代码了!谢谢你的帮助!非常高兴听到这个消息!谢谢@MarkusHauschel,很荣幸!事实上,是的,这只是我之前的答案的剩余部分。这里使用
str.format
将其精确到我们想要的精度,然后用正确的精度替换该值,但您可以将其保留在这里,或者将其强制转换为
float
:-)
0.00725562
0.007256
0.007255