Search code examples
pythonlocalecurrency

Currency with 3 decimal digits in python


I have the following code which compares the input value that comes as a string with the one the function constracts. Basically checks the if the number the user enters is correct. The function works but only for 2 decimal points but the user is allowed to enter 2 to 4 decimal digits... How can I construct the right value?

def check_currency(self, amount):
        amount = amount.replace("+", "")
        amount = amount.replace("-", "")
        sInput = amount.replace(",", ".")
        locale.setlocale(locale.LC_ALL, self.LANG)
        result = locale.currency(float(sInput), symbol=False, grouping=True)
        if (amount == result):
            return True
        else:
            return False

PS: The self.LANG get the respective value based on the system that the code runs on.


Solution

  • You aren't missing anything. locale.currency formats numbers according to the values in the dict returned by locale.localeconv() and that's what it's supposed to do. Naturally, 'frac_digits' is typically 2 since... well... you know.


    Regarding what to do:

    First, you can check 'int_frac_digits' in localeconv() - maybe it's good enough for you.

    If not, since locale.currency is located in a Python source module, you can rig... I mean, override its logic. Looking at the source, the simplest method appears to be to replace locale.localeconv() with a wrapper.

    Be wary though since such a change will be global. If you don't want it to affect other code using locale, alter local copies of the entities (or the entire module) or make a changed entity e.g. require an additional parameter to behave differently.


    On a conceptual note: locale is actually correct - for its purpose - in not allowing to alter the representation. Its task is to format information of a few types according to the local convention - so whatever culture you user pertains to, they will see information in the way they are used to. If you alter the format in any way - that wouldn't any longer be "the local convention"! In fact, by requiring 3 decimal digits, you are already making assumptions about the local convention - which may not stand. E.g. in a decent share of currencies, even small sums can numerically be in the thousands.