首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >向上舍入到Python中的第二位小数

向上舍入到Python中的第二位小数
EN

Stack Overflow用户
提问于 2012-02-11 01:41:24
回答 8查看 131.2K关注 0票数 61

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

0.022499999999999999

应四舍五入为0.03

0.1111111111111000

应四舍五入为0.12

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

EN

回答 8

Stack Overflow用户

发布于 2012-02-11 01:44:28

from math import ceil

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

请参见:

math.ceil documentation

round documentation -无论如何,您都可能想要检查一下这篇文章,以便将来参考

票数 32
EN

Stack Overflow用户

发布于 2012-02-11 01:45:31

x = math.ceil(x * 100.0) / 100.0
票数 19
EN

Stack Overflow用户

发布于 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
票数 16
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9232256

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档