Dennis
Dennis

Reputation: 121

Currency symbol oddity in Python. Same code, different system, different outcome why?

The currency symbol is not always a symbol. How to ensure that it is always a symbol and not a 2 char string?

Example:

import locale

locale.setlocale(locale.LC_ALL, 'de_DE')
conv=locale.localeconv()
print('Currency code:', conv['int_curr_symbol'])
print('Currency symbol:', conv['currency_symbol'])

On some systems the result for currency symbol is "€" on others it is "Eu"

I did find a way to, at least so far, get a consistent currency symbol on all systems with the help of "forex_python" package.

Example:

from forex_python.converter import CurrencyCodes
print('Currency symbols')
c = CurrencyCodes()
print('GBP:', c.get_symbol('GBP'))
print('EUR:',c.get_symbol('EUR'))
print('THB:',c.get_symbol('THB'))
print('USD', c.get_symbol('USD'))

Upvotes: 3

Views: 639

Answers (2)

Dennis
Dennis

Reputation: 121

Since using the locale is only useful related to the local machine an alternative solution is required.

I found the Python library forex_python. See working code example on repl.it: https://repl.it/join/jitjazjz-dmenis

from forex_python.converter import CurrencyCodes

print('Currency symbols')
c = CurrencyCodes()
print('GBP:', c.get_symbol('GBP'))
print('EUR:',c.get_symbol('EUR'))
print('THB:',c.get_symbol('THB'))
print('USD', c.get_symbol('USD'))

So for now I'll go with forex_python but if I need additional functionality for rounding etc then I'll consider py-currency (nh-currency) or perhaps django-money.

Also forex_python seems to be an active project on Github maintained by a Company that specialises in Python developments https://micropyramid.com/

Upvotes: 1

Gopinath
Gopinath

Reputation: 4957

nh-currency library of Python provides one of the best solutions for processing currency information.

Here is a working demo printing currency symbols:

# File name:      currency-symbols-demo.py
# Pre-requisite:  pip3 install nh-currency

import currency

print('INR : ' + currency.symbol('INR'))
print('GBP : ' + currency.symbol('GBP'))
print('EUR : ' + currency.symbol('EUR'))
print('USD : ' + currency.symbol('USD'))

Output:

$ python3 currency-symbols-demo.py 

INR : ₹
GBP : £
EUR : €
USD : $

More information:

https://pypi.org/project/nh-currency/

Upvotes: 3

Related Questions