字典中的数字舍入

问题描述 投票:0回答:2

我有一个 python 3.4 程序,可以打印字典中的一些数字,但这些数字有很长的小数位。如何让它打印没有小数位的词典?

python dictionary rounding
2个回答
3
投票

如果您只想截去小数,则可以使用

int()
;如果您想在给定精度的情况下四舍五入到更接近的数字,则可以使用
round()
,即
round(2.456,1)=2.5
round(2.456,0)=2


2
投票

您可以使用

int

for k,v in your_dic.items():
    print k,int(v)

演示:

>>> int(1.000000000000000001)
1

字符串格式:

>>> x = 1.000000000000000001
>>> print "{:.0f}".format(x)
1
>>> print format(x,'.0f')
1
© www.soinside.com 2019 - 2024. All rights reserved.