4

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?

kylieCatt
  • 10,094
  • 5
  • 40
  • 51
Mike Sr
  • 501
  • 1
  • 5
  • 12
  • Forgot to add this line of code: locale.setlocale( locale.LC_ALL, 'English_United States.1252' ) – Mike Sr May 15 '15 at 11:40
  • 1
    Why? It's pretty common to use parenthesis to indicate negative currency/ – kylieCatt May 15 '15 at 11:48
  • Also forgot to add that this is Windows 7 x64 – Mike Sr May 16 '15 at 21:28
  • As to why? I am storing data in a pyQT Table and I have to convert it to place it in the Table and convert it coming out. Being a novice I couldn't find a way to get around the errors when doing the string to Decimal conversions. While waiting I ended up writing my own toCurrency function that accepts a QString, String or Decimal. – Mike Sr May 16 '15 at 21:31

2 Answers2

3

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.

Community
  • 1
  • 1
John
  • 12,723
  • 7
  • 48
  • 99
0

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
  • I get this error: Traceback (most recent call last): File "D:/Python Projects/Budget/Budget.pyw", line 168, in locale.setlocale(locale.LC_ALL, b'en_US.UTF-8') File "C:\Python27\lib\locale.py", line 579, in setlocale return _setlocale(category, locale) locale.Error: unsupported locale setting – Mike Sr May 16 '15 at 21:27
  • @user3279899 what version of python? –  May 17 '15 at 15:27
  • Python 2.7 is the version I am running – Mike Sr May 18 '15 at 22:12