3

我需要四舍五入一个浮点数。例如 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

我找不到这个问题(为什么?)。有没有我错过的其他模块或功能?拥有一个具有基本(更改)功能的大型库会很棒。

编辑:我不谈论整数。

4

1 回答 1

3

从这篇 SO 帖子中查看我的答案。您应该能够通过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
于 2018-08-18T07:32:56.137 回答