x="1,234.00"
y =x.replace(',','')
k = float(y)
print k
output=1234.0 but i need 1234.00 value please solve this problem
x="1,234.00"
y =x.replace(',','')
k = float(y)
print k
output=1234.0 but i need 1234.00 value please solve this problem
1234.0 和 1234.00 之间的值没有差异。您不能在浮点数中保存更多或更少的非有效数字。但是,您可以打印更多或更少(非)有效数字。在旧版本的 python 中,您可以使用该%
方法(文档)。在 Python 2.7 及更高版本中,使用字符串格式方法。一个例子:
f = float('156.2')
# in Python 2.3
no_decimals = "%.0f" % f
print no_decimals # "156" (no decimal numbers)
five_decimals = "%.5f" % f
print five_decimals # "156.20000" (5 decimal numbers)
# in Python 2.7
no_decimals = "{:.0f}".format(f)
print no_decimals # "156" (no decimal numbers)
five_decimals = "{:.5f}".format(f)
print five_decimals # "156.20000" (5 decimal numbers)
如果由于某种原因您无法访问打印值的代码,您可以创建自己的类,继承float
并提供您自己的__str__
值。这可能会破坏某些行为(它不应该,但它可以),所以要小心。这是一个例子:
class my_float(float):
def __str__(self):
return "%.2f" % self
f = my_float(1234.0)
print f # "1234.00"
(我在 Python 2.7 上运行,我没有安装 2.3;请考虑将 Python 升级到 2.7 或 3.5;2.3 严重过时。)