Search code examples
pythonlocalenumber-formatting

deformat locale number string back to number


I can create a locale Number string via

import locale
locale.setlocale(locale.LC_ALL, 'de_DE.utf8')
numberstring = '{0:n}'.format(number)

(I found this on this stackoverflow answer.)

Now, I have an input from the user. I don't know whether it is a valid locale number string or not. If it is, I want to convert it to a number. If it is not, I want to send an error and let him retry.

What is the best-practice solution i.e. the one that uses the functions from the locale lib that are meant for this? (I guess this does exist?)


Solution

  • Doesn't locale.delocalize solve your problem? For example:

    import locale
    
    locale.setlocale(locale.LC_ALL, 'de_DE.utf8')
    numberstring = '{0:n}'.format(1700.5)   # "1 700,5"
    normalized = locale.delocalize(numberstring)  # "1700.5"
    try:
        number = float(normalized)  # 1700.5
    except ValueError:
        # Not a number