开发者

Python how to format currency string

I have three floats that I want to output as a 2 decimal places string.

amount1 = 0.1
amount2 = 0.0
amount3 = 1.87

I want to output all of them as a string that looks like 0.10, 0.00, and 1.87 respectively.

How do I do that efficie开发者_开发百科ntly?


An alternative to directly formatting them is the locale stdlib module

>>> 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'

This is nice because you can just set the locale to the users default as I do and then print in their conventions.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜