Search code examples
pythonsetlocale

python setlocale does not work


I cannot make setlocale to work. hr_HR should recognise comma as decimal deliminator, and it does not. What am I missing? I'm on Ubuntu 14.10, python 2.7

>>> import locale
>>> float("3.2")
3.2
>>> float("3,2")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for float(): 3,2
>>> locale.setlocale(locale.LC_NUMERIC, 'hr_HR.utf8')
'hr_HR.utf8'
>>> float("3.2")
3.2
>>> float("3,2")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for float(): 3,2
>>> locale.setlocale(locale.LC_ALL, 'hr_HR.utf8')
'hr_HR.utf8'
>>> float("3.2")
3.2
>>> float("3,2")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for float(): 3,2
>>> 

Solution

  • You seem to want the locale.atof(string) fuction. From the documentation:

    locale.atof(string)

    Converts a string to a floating point number, following the LC_NUMERIC settings.

    From the documentation, it doesn't look like setlocal changes how the builtins work but gives one a different of function that do similar things.