在python中,如何将一个数字四舍五入到小数点后第二位?例如:
0.022499999999999999
应四舍五入为0.03
0.1111111111111000
应四舍五入为0.12
如果在小数点的第三位有任何值,我希望它总是四舍五入,在小数点后留下两个值。
发布于 2012-02-11 01:44:28
from math import ceil
num = 0.1111111111000
num = ceil(num * 100) / 100.0
请参见:
round
documentation -无论如何,您都可能想要检查一下这篇文章,以便将来参考
发布于 2012-02-11 01:45:31
x = math.ceil(x * 100.0) / 100.0
发布于 2012-02-11 02:09:38
从埃德温的答案推断:
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
https://stackoverflow.com/questions/9232256
复制相似问题