python 以千位逗号分隔值,不带尾随零

python comma separate values by thousands without trailing zeros

我正在尝试用逗号分隔浮点数。我可以使用 locale.format() 函数来做到这一点。但是预期的输出没有考虑小数点。

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'