python locale 货币格式化为0位小数

4 投票
2 回答
3853 浏览
提问于 2025-04-18 05:07

我搞不清楚怎么把我的货币设置为0位小数。现在它总是会在我的货币后面加上.00。

locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
damn = locale.currency(self.damn, grouping=True).replace('$','') + " Dmn"

self.damn始终是一个整数。

2 个回答

1

输出是一个字符串,所以在最后加上[:-3]:

a = locale.currency(num, grouping=True)[:-3]
6

看起来你只是想把数字分组。其实你不需要用货币格式的函数来实现这个。可以用 locale.format() 来处理:

import locale
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
damn = '{0} Dmn'.format(locale.format('%d', self.damn, True))

如果你不需要依赖 locale 的东西,也可以用 string.format() 来分组数字:

# Comma as separator
damn = '{:,} Dmn'.format(self.damn)
# Locale aware separator
damn = '{:n} Dmn'.format(self.damn)

撰写回答