问题
I haven't found anything that addresses how to format negative currency, so far, and it is driving me crazy.
from decimal import *
import re
import sys
import os
import locale
locale.setlocale( locale.LC_ALL, 'English_United States.1252' )
# cBalance is a running balance of type Decimal
fBalance = locale.currency( cBalance, grouping=True )
print cBalance, fBalance
Result with Negative Number:
-496.06 ($496.06)
I need a minus sign NOT parenthesis
How do I get rid of the parenthesis and get minus signs?
回答1:
Looks like you can use the _override_localeconv
dict (which is a bit hackish).
import locale
cBalance = -496.06
locale.setlocale( locale.LC_ALL, 'English_United States.1252')
locale._override_localeconv = {'n_sign_posn':1}
fBalance = locale.currency(cBalance, grouping=True)
print cBalance, fBalance
or you could use string formatting.
回答2:
This may not be the comprehensive approach you seek, but if you use the locale en_US.UTF-8
, you can have a deterministic approach with the the negative sign -
:
import locale
locale.setlocale(locale.LC_ALL, b'en_US.UTF-8')
amount = locale.currency(-350, grouping=True)
print(amount) # -$350.00
amount = locale.currency(-350, grouping=True).replace('$', '')
print(amount) # -350.00
来源:https://stackoverflow.com/questions/30258593/python-format-negative-currency