python round留下一个尾随的0

2024-04-27 13:11:17 发布

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

我试图将python中的浮点数舍入到小数点后零位。

但是,round方法每次都会留下一个尾随的0。

value = 10.01
rounded_value = round(value)
print rounded_value

结果是10.0但我想要10

如何才能做到这一点?转换为int?


Tags: 方法valueintprint浮点数小数点roundrounded
3条回答

将舍入值传递给int()以删除小数位数:

>>> value = 10.01
>>> int(round(value))
10
>>> value = 10.55
>>> int(round(value))
11

10.010是相同的float值。当您print该值时,您将获得字符串10.0,因为这是该值的默认字符串表示形式。(与通过调用str(10.0)获得的字符串相同。)

如果需要非默认表示,则需要显式地请求它。例如,使用^{}函数:

print format(rounded_value, '.0f')

或者,使用其他格式化方法:

print '{:.0f}'.format(rounded_value)
print '%.0f' % (rounded_value,)

关于为什么需要'.0f'的完整细节在Format Specification Mini-Language中有描述,但直观地说:f表示需要定点格式(比如10.0,而不是1.0E2),而.0表示小数点后不需要数字(比如10,而不是10.0)。

同时,如果只是原因,那么该值是用于格式化的……永远不要这样做。将精度保留在浮点上,然后在格式中向下修剪:

print format(value, '.0f')

转换为int肯定是最简单的方法。如果你执意要让它浮起来,这里有亚历克斯·马泰利的介绍:

print ('%f' % value).rstrip('0').rstrip('.')

相关问题 更多 >