我正在尝试将 python 中的浮点数四舍五入到零小数位。
但是,round 方法每次都会留下一个尾随 0。
value = 10.01
rounded_value = round(value)
print rounded_value
结果为 10.0 但我想要 10
如何做到这一点?转换成int?
我正在尝试将 python 中的浮点数四舍五入到零小数位。
但是,round 方法每次都会留下一个尾随 0。
value = 10.01
rounded_value = round(value)
print rounded_value
结果为 10.0 但我想要 10
如何做到这一点?转换成int?
将四舍五入的值传递给以int()
去除小数位:
>>> value = 10.01
>>> int(round(value))
10
>>> value = 10.55
>>> int(round(value))
11
10.0
并且10
是相同的float
值。当您print
获得该值时,您将获得 string 10.0
,因为这是该值的默认字符串表示形式。(您通过调用获得的相同字符串str(10.0)
。)
如果你想要一个非默认的表示,你需要明确地要求它。例如,使用format
函数:
print format(rounded_value, '.0f')
或者,使用其他格式化方法:
print '{:.0f}'.format(rounded_value)
print '%.0f' % (rounded_value,)
Format Specification Mini-Language'.0f'
中描述了您想要的全部详细信息,但直观地说:您想要定点格式的方式(例如,而不是,说,),以及您想要小数点后没有数字的方式(例如而不是)。f
10.0
1.0E2
.0
10
10.0
同时,如果您编辑该值的唯一原因round
是格式化......永远不要这样做。将精度保留在浮点数上,然后在格式中对其进行修剪:
print format(value, '.0f')
转换为 int 肯定是最简单的方法。如果你一心想要让它保持浮动,这里是由 Alex Martelli 提供的如何做到这一点:
print ('%f' % value).rstrip('0').rstrip('.')
您会在这篇文章number_shaver()
的 EDIT 2 中找到一个删除数字尾随零的函数。
同一线程中的另一篇文章解释了正则表达式的number_shaver()
工作原理。
几天后,我在另一个线程中改进了正则表达式。