Python format negative currency

那年仲夏 提交于 2019-12-10 16:08:42

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!