Pablo Guerrero
Pablo Guerrero

Reputation: 1074

How to format a number with spanish thousand grouping in python?

I need to format a number with Spanish thousand separators (points instead of commas). Using locale, I can get the separators for English:

>>> import locale
>>> locale.setlocale(locale.LC_ALL, 'en_US')
'en_US'
>>> print(locale.format("%d", 10000000, grouping=True))
10,000,000

However, if I try to obtain the Spanish separators, it doesn't work:

>>> locale.setlocale(locale.LC_ALL, 'es_ES')
'es_ES'
>>> print(locale.format("%d", 10000000, grouping=True))
10000000

Any ideas on how to obtain the expected result? (10.000.000). I am using python 3.4.

Upvotes: 2

Views: 2742

Answers (2)

xnx
xnx

Reputation: 25548

I think the es_ES numeric formatting does not include a thousands separator. The monetary formatting does, however:

In [16]: locale.setlocale(locale.LC_ALL, 'es_ES')
In [17]: print(locale.format('%d', 10000000, grouping=True, monetary=True))
10.000.000

You can get more information by calling locale.localeconv():

In [18]: locale.localeconv()
Out[18]: 
{'currency_symbol': 'Eu',
 'decimal_point': ',',
 'frac_digits': 2,
 'grouping': [127],
 'int_curr_symbol': 'EUR ',
 'int_frac_digits': 2,
 'mon_decimal_point': ',',
 'mon_grouping': [3, 3, 0],
 'mon_thousands_sep': '.',     # <----- NB
 'n_cs_precedes': 0,
 'n_sep_by_space': 1,
 'n_sign_posn': 1,
 'negative_sign': '-',
 'p_cs_precedes': 0,
 'p_sep_by_space': 1,
 'p_sign_posn': 1,
 'positive_sign': '',
 'thousands_sep': ''}         # <----- NB

Upvotes: 3

Stidgeon
Stidgeon

Reputation: 2723

I tried this in Python 2.7 (in Windows), and it seemed to work, but my locale setting was a bit different:

>>>locale.setlocale(locale.LC_ALL, 'esp_esp')
'Spanish_Spain.1252'
>>>print(locale.format('%d', 10000000, grouping=True))
10.000.000

Which Python version are you using? (this may not be an answer, but I'm unable to use comments . . . sorry!)

Upvotes: 2

Related Questions