[英]Python float decimal places
在python中,假设我想快速轻松地将我的浮点数格式化为两位或更少的小数位,例如:
1.234 -> 1.23
1.2 -> 1.2
1 -> 1
2. -> 2
我应该使用什么方法? 我可以将其格式化为2个小数位固定但不能想到一个快速的方法,使其2或更少的小数位。
我建议使用round
功能
In [1]: round(1.234, 2)
Out[1]: 1.23
In [2]: round(1.2, 2)
Out[2]: 1.2
不幸的是,它有一个缺点:它会将你的int
转换为float
s(在python2.x中。但它会将它们保存为python3.x中的int
):
In [3]: round(1,2)
Out[3]: 1.0
对于格式化打印使用:
print "%.2f" % 1.234 # -> 1.23
print "%.1f" % 1.234 # -> 1.2
print "%.0f" % 2. # -> 2
格式化到两个地方后,只需使用一点蛮力。
>>> '{:.2f}'.format(1.234).rstrip('0').rstrip('.')
'1.23'
>>> '{:.2f}'.format(1.2).rstrip('0').rstrip('.')
'1.2'
>>> '{:.2f}'.format(1).rstrip('0').rstrip('.')
'1'
>>> '{:.2f}'.format(2.).rstrip('0').rstrip('.')
'2'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.