在Python中四舍五入到小数点后第二位

2024-05-15 08:39:34 发布

您现在位置:Python中文网/ 问答频道 /正文

在python中,如何将数字四舍五入到小数点后第二位?例如:

0.022499999999999999

应舍入到0.03

0.1111111111111000

应该四舍五入到0.12

如果第三个小数位有任何值,我希望它总是四舍五入,在小数点后留下两个值。


Tags: 数字小数点小数位
3条回答

根据埃德温的回答推断:

from math import ceil, floor
def float_round(num, places = 0, direction = floor):
    return direction(num * (10**places)) / float(10**places)

使用:

>>> float_round(0.21111, 3, ceil)  #round up
>>> 0.212
>>> float_round(0.21111, 3)        #round down
>>> 0.211
>>> float_round(0.21111, 3, round) #round naturally
>>> 0.211

Python包含round()函数,该函数lets you specify您需要的位数。从文档中:

round(x[, n])

Return the floating point value x rounded to n digits after the decimal point. If n is omitted, it defaults to zero. The result is a floating point number. Values are rounded to the closest multiple of 10 to the power minus n; if two multiples are equally close, rounding is done away from 0 (so. for example, round(0.5) is 1.0 and round(-0.5) is -1.0).

所以您需要使用round(x, 2)来进行正常舍入。为了确保数字总是向上舍入您需要使用ceil(x)函数。同样,要将向下取整使用floor(x)

from math import ceil

num = 0.1111111111000
num = ceil(num * 100) / 100.0

见:
^{} documentation
^{} documentation-你可能还是想看看这个,以备将来参考

相关问题 更多 >