圆形浮动十进制数UP

时间:2017-01-06 15:05:20

标签: python floating-point integer

我目前在python中使用浮动小数舍入数字。我认为这些数字被整理为整数,但我怀疑......

确保向上舍入到最接近的整数的最佳方法是什么?

" snw"的数据变量

0
0
0
1.5
0
0.5
0
1
1
0
0
0
0
0
0
0
0
0
1

Python代码:

for i in range(len(snw)):
    fmt=r"%5.0f" % (snw[i])

1 个答案:

答案 0 :(得分:0)

目前还不清楚你的目标究竟是什么行为。

如果您想要将所有数字四舍五入(即0.1到1),那么最简单的选择是拨打math.ceil

>>> import math
>>> math.ceil(0.1)
1.0
>>> r"%5.0f" % math.ceil(0.1)
'    1'

另一方面,如果你想改变关系的处理方式(即1/2的小数部分的数字),如果你使用的是Python 2,你可以使用round

>>> round(0.5)
1.0
>>> r"%5.0f" % round(0.5)
'    1'

但请注意,Python 3将round的行为更改为使用“tie to even even”,因此在这种情况下,您需要执行其他操作。我最喜欢的是以下内容:

import math
def oldround(x):
    y = x - math.trunc(x)
    return math.trunc(x+y)
相关问题