Python浮点小数位

时间:2014-01-28 21:50:08

标签: python

在python中,假设我想快速轻松地将我的浮点数格式化为两位或更少的小数位,例如:

1.234 -> 1.23

1.2 -> 1.2

1  -> 1

2. -> 2

我应该使用什么方法?我可以将它格式化为2个小数位固定但不能想到一个快速的方法,使其小数点后2位或更少。

3 个答案:

答案 0 :(得分:7)

我建议使用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中。它会将它们保存为int在python3.x中,虽然):

In [3]: round(1,2)
Out[3]: 1.0

答案 1 :(得分:2)

对于格式化打印使用:

print "%.2f" % 1.234  # -> 1.23
print "%.1f" % 1.234  # -> 1.2
print "%.0f" % 2.     # -> 2

答案 2 :(得分:1)

格式化后,只需使用一点蛮力到两个地方。

>>> '{:.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'