0

I want to implement inside a function localized formatting so that the typed in value 12,3 is recognized as a float

import locale

def localize(argument):
    if argument == "do it":

        locale.setlocale(category=locale.LC_ALL,
                 locale="German")
#         locale.setlocale(locale.LC_ALL, 'deu_deu')


          x = float(input("type in a float"))

          print(x)

    else:
        pass


I tried every commbination from this thread correct way to set Python's locale on Windows? but so far its not working, Im aware that that the change can be implemented without localized formatting, but I want to do this in this particulare way

Sator
  • 636
  • 4
  • 13
  • 34

1 Answers1

0

To change locale only in one specific place, use a context manager and with statement to revert locale after the block. Use locale.atof function to parse float according to locale and {:n} to format according to locale.

import locale
from contextlib import contextmanager

@contextmanager
def localized(code):
    old_code, old_encoding = locale.getlocale()
    locale.setlocale(locale.LC_ALL, code)
    yield
    locale.setlocale(locale.LC_ALL, f"{old_code}.{old_encoding}")

with localized("pl_PL.utf8"):
    x = locale.atof("3,5")
    print(x) # 3.5
    print(f"{x:n}") # 3,5
    print("{:n}".format(x)) # 3,5
RafalS
  • 5,834
  • 1
  • 20
  • 25
  • is this working for you ? , I guess you have linux, I dont know how it can return a float in the first place, when I type in `12,3` it is going to be a tuple, – Sator May 02 '20 at 14:52
  • Yeah, I focused mostly on the reversing mechanism. I edited the answer. `locale.atof` did the trick on linux. Let me know if it works on windows – RafalS May 02 '20 at 17:15
  • if I type in `12,3` in the input is the output from `print(x)` also `12,3` ? – Sator May 03 '20 at 10:12
  • Not by default, but you can use string formatting to respect locale in formatting numbers. See the edited answer. – RafalS May 03 '20 at 13:53
  • I have found a workaround using regex but I may need your aproach later – Sator May 03 '20 at 14:25