python逗号由千位分隔的数值无尾随零
问题描述:
我想用逗号分隔浮动金额数千。我能够使用locale.format()函数来实现这一点。但预期的产出不考虑小数点。python逗号由千位分隔的数值无尾随零
import locale
locale.setlocale(locale.LC_ALL, 'en_US')
amount = locale.format('%d', 10025.87, True)
amount
'10,025'
我的预期产出应该是10,025.87,保持尾随值。请让我知道,如果这种事情是可能的
Value: 1067.00
Output: 1,067
Value: 1200450
Output: 1,200,450
Value: 1340.9
Output: 1,340.9
答
如何:
import locale
locale.setlocale(locale.LC_ALL, 'en_US')
# strip any potential trailing zeros because %f is used.
amount = locale.format('%f', 10025.87, True).rstrip('0').rstrip('.')
amount # '10,025.87'
+0
这一个工程,但它并没有删除'。'需要做一个额外的'.rstrip('。')'。我现在正在做的是amount = locale.format('%f',10025.00,True).rstrip('0')。rstrip('。') –
+0
是的。如果只有数千个存在,则更新我的答案以删除尾部“。”。 –
%d是一个整数格式代码。尝试使用%f –
奥斯汀黑斯廷斯和manvi77,是的它的工作原理,但它随着它离开了大量的尾随零。必须结合使用rstrip来删除它们。非常感谢 –