Python如何格式化货币字符串

Alb*_*ert 3 python string

我有三个浮点数,我想输出为2位小数字符串.

amount1 = 0.1
amount2 = 0.0
amount3 = 1.87
Run Code Online (Sandbox Code Playgroud)

我想将它们全部输出为分别为0.10,0.00和1.87的字符串.

我该如何有效地做到这一点?

aar*_*ing 5

直接格式化它们的替代方法是locale stdlib模块

>>> import locale
>>> locale.setlocale(locale.LC_ALL, '')
'en_US.utf8'
>>> locale.currency(123.2342343234234234)
'$123.23'
>>> locale.currency(123.2342343234234234, '')  # the second argument controls the symbol
'123.23'
Run Code Online (Sandbox Code Playgroud)

这很好,因为您可以像我一样将语言环境设置为用户默认值,然后在其约定中打印.