I've spent considerable time of getting that right, there are three main issues that differs from locale to locale:
- currency symbol and direction
- thousand separator
- decimal point
I've written my own rather extensive implementation of this which is part of the kiwi python framework, check out the LGPL:ed source here:
If you are using OSX and have yet to set your locale module setting this first answer will not work you will receive the following error:
Traceback (most recent call last):File "<stdin>", line 1, in <module> File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/locale.py", line 221, in currency
raise ValueError("Currency formatting is not possible using "ValueError: Currency formatting is not possible using the 'C' locale.
To remedy this you will have to do use the following:
Not quite sure why it's not mentioned more online (or on this thread), but the Babel package (and Django utilities) from the Edgewall guys is awesome for currency formatting (and lots of other i18n tasks). It's nice because it doesn't suffer from the need to do everything globally like the core Python locale module.
#printing the variable 'Total:' in a format that looks like this '9,348.237'
print ('Total:', '{:7,.3f}'.format(zum1))
where the '{:7,.3f}' es the number of spaces for formatting the number in this case is a million with 3 decimal points.
Then you add the '.format(zum1). The zum1 is tha variable that has the big number for the sum of all number in my particular program. Variable can be anything that you decide to use.
def format_us_currency(value):
value=str(value)
if value.count(',')==0:
b,n,v='',1,value
value=value[:value.rfind('.')]
for i in value[::-1]:
b=','+i+b if n==3 else i+b
n=1 if n==3 else n+1
b=b[1:] if b[0]==',' else b
value=b+v[v.rfind('.'):]
return '$'+(value.rstrip('0').rstrip('.') if '.' in value else value)
There are already a dozen solutions here, but I believe the one below is the best, because:
it is simple
obeys the OS locale
no external lib is needed
you can make it concise
Use locale.currency() method:
import locale
# this sets locale to the current Operating System value
locale.setlocale(locale.LC_ALL, '')
print(locale.currency(1346896.67444, grouping=True, symbol=True)
will output in my Windows 10 configured to Brazilian Portuguese:
R$ 1.346.896,67
It is somewhat verbose, so if you will use it a lot, maybe it is better to predefine some parameters and have a shorter name and use it inside a f-string:
You can pass a locale value for the setlocale method, but its value is OS dependent, so beware. If you are in a *nix server, you also need to check if the locale is correctly installed in the OS.
You also can turn off the symbol passing symbol=False.