Example #1
0
    def __new__(cls, value):
        """
        Convert value to currency.
        :param value: value to convert
        :type value: string or number
        """
        if isinstance(value, str):
            conv = get_localeconv()
            currency_symbol = conv.get('currency_symbol')
            text = value.strip(currency_symbol)
            # if we cannot convert it using locale information, still try to
            # create
            try:
                text = filter_locale(text, monetary=True)
                value = currency._converter.from_string(text, filter=False)
            except ValidationError:
                # Decimal does not accept leading and trailing spaces. See
                # bug 1516613
                value = text.strip()

            if value == ValueUnset:
                raise decimal.InvalidOperation
        elif isinstance(value, float):
            print('Warning: losing precision converting float %r to currency' %
                  value)
            value = str(value)
        elif not isinstance(value, (int, decimal.Decimal)):
            raise TypeError("cannot convert %r of type %s to a currency" %
                            (value, type(value)))

        return decimal.Decimal.__new__(cls, value)
Example #2
0
    def __new__(cls, value):
        """
        Convert value to currency.
        :param value: value to convert
        :type value: string or number
        """
        if isinstance(value, six.string_types):
            conv = get_localeconv()
            currency_symbol = conv.get('currency_symbol')
            text = value.strip(currency_symbol)
            # if we cannot convert it using locale information, still try to
            # create
            try:
                text = filter_locale(text, monetary=True)
                value = currency._converter.from_string(text,
                                                        filter=False)
            except ValidationError:
                # Decimal does not accept leading and trailing spaces. See
                # bug 1516613
                value = text.strip()

            if value == ValueUnset:
                raise decimal.InvalidOperation
        elif isinstance(value, float):
            print('Warning: losing precision converting float %r to currency'
                  % value)
            value = six.text_type(value)
        elif not isinstance(value, (int, decimal.Decimal)):
            raise TypeError(
                "cannot convert %r of type %s to a currency" % (
                    value, type(value)))

        return decimal.Decimal.__new__(cls, value)
Example #3
0
    def _setup_kiwi(self):
        from kiwi.ui.views import set_glade_loader_func
        set_glade_loader_func(self._glade_loader_func)

        from kiwi.datatypes import get_localeconv
        from kiwi.ui.widgets.label import ProxyLabel
        ProxyLabel.replace('$CURRENCY', get_localeconv()['currency_symbol'])
Example #4
0
    def _setup_kiwi(self):
        from kiwi.ui.views import set_glade_loader_func
        set_glade_loader_func(self._glade_loader_func)

        from kiwi.datatypes import get_localeconv
        from kiwi.ui.widgets.label import ProxyLabel
        ProxyLabel.replace('$CURRENCY', get_localeconv()['currency_symbol'])
Example #5
0
 def _setup_kiwi(self):
     from kiwi.datatypes import get_localeconv
     from kiwi.ui.widgets.label import ProxyLabel
     ProxyLabel.replace('$CURRENCY', get_localeconv()['currency_symbol'])
Example #6
0
    def format(self, symbol=True, precision=None):
        conv = get_localeconv()

        frac_digits = precision or conv.get('frac_digits', 2)
        # Decimal.quantize can't handle a precision of 127, which is
        # the default value for glibc/python. Fallback to 2
        if frac_digits == 127:
            frac_digits = 2
        value = self.quantize(decimal.Decimal('10')**-frac_digits)

        # Grouping (eg thousand separator) of integer part
        groups = conv.get('mon_grouping', [])[:]
        groups.reverse()
        if groups:
            group = groups.pop()
        else:
            group = 3

        intparts = []

        # We're iterating over every character in the integer part
        # make sure to remove the negative sign, it'll be added later
        intpart = str(int(abs(value)))

        while True:
            if not intpart:
                break

            s = intpart[-group:]
            intparts.insert(0, s)
            intpart = intpart[:-group]
            if not groups:
                continue

            last = groups.pop()
            # if 0 reuse last one, see struct lconv in locale.h
            if last != 0:
                group = last

        # Add the sign, and the list of decmial parts, which now are grouped
        # properly and can be joined by mon_thousand_sep
        if value > 0:
            sign = conv.get('positive_sign', '')
        elif value < 0:
            sign = conv.get('negative_sign', '-')
        else:
            sign = ''
        currency = sign + conv.get('mon_thousands_sep', '.').join(intparts)

        # Only add decimal part if it has one, is this correct?
        if precision is not None or value % 1 != 0:
            sign_, digits, exponent = value.as_tuple()
            frac = digits[exponent:] if exponent != 0 else (0, )
            dec_part = ''.join(str(i) for i in frac)
            # Add 0s to complete the required precision
            dec_part = dec_part.rjust(frac_digits, '0')

            mon_decimal_point = conv.get('mon_decimal_point', '.')
            currency += mon_decimal_point + dec_part

        # If requested include currency symbol
        currency_symbol = conv.get('currency_symbol', '')
        if currency_symbol and symbol:
            if value > 0:
                cs_precedes = conv.get('p_cs_precedes', 1)
                sep_by_space = conv.get('p_sep_by_space', 1)
            else:
                cs_precedes = conv.get('n_cs_precedes', 1)
                sep_by_space = conv.get('n_sep_by_space', 1)

            if sep_by_space:
                space = ' '
            else:
                space = ''
            if cs_precedes:
                currency = currency_symbol + space + currency
            else:
                currency = currency + space + currency_symbol

        return currency
Example #7
0
    def format(self, symbol=True, precision=None):
        conv = get_localeconv()

        frac_digits = precision or conv.get('frac_digits', 2)
        # Decimal.quantize can't handle a precision of 127, which is
        # the default value for glibc/python. Fallback to 2
        if frac_digits == 127:
            frac_digits = 2
        value = self.quantize(decimal.Decimal('10') ** -frac_digits)

        # Grouping (eg thousand separator) of integer part
        groups = conv.get('mon_grouping', [])[:]
        groups.reverse()
        if groups:
            group = groups.pop()
        else:
            group = 3

        intparts = []

        # We're iterating over every character in the integer part
        # make sure to remove the negative sign, it'll be added later
        intpart = str(int(abs(value)))

        while True:
            if not intpart:
                break

            s = intpart[-group:]
            intparts.insert(0, s)
            intpart = intpart[:-group]
            if not groups:
                continue

            last = groups.pop()
            # if 0 reuse last one, see struct lconv in locale.h
            if last != 0:
                group = last

        # Add the sign, and the list of decmial parts, which now are grouped
        # properly and can be joined by mon_thousand_sep
        if value > 0:
            sign = conv.get('positive_sign', '')
        elif value < 0:
            sign = conv.get('negative_sign', '-')
        else:
            sign = ''
        currency = sign + conv.get('mon_thousands_sep', '.').join(intparts)

        # Only add decimal part if it has one, is this correct?
        if precision is not None or value % 1 != 0:
            sign_, digits, exponent = value.as_tuple()
            frac = digits[exponent:] if exponent != 0 else (0, )
            dec_part = ''.join(str(i) for i in frac)
            # Add 0s to complete the required precision
            dec_part = dec_part.rjust(frac_digits, '0')

            mon_decimal_point = conv.get('mon_decimal_point', '.')
            currency += mon_decimal_point + dec_part

        # If requested include currency symbol
        currency_symbol = conv.get('currency_symbol', '')
        if currency_symbol and symbol:
            if value > 0:
                cs_precedes = conv.get('p_cs_precedes', 1)
                sep_by_space = conv.get('p_sep_by_space', 1)
            else:
                cs_precedes = conv.get('n_cs_precedes', 1)
                sep_by_space = conv.get('n_sep_by_space', 1)

            if sep_by_space:
                space = ' '
            else:
                space = ''
            if cs_precedes:
                currency = currency_symbol + space + currency
            else:
                currency = currency + space + currency_symbol

        return currency
Example #8
0
 def _setup_kiwi(self):
     from kiwi.datatypes import get_localeconv
     from kiwi.ui.widgets.label import ProxyLabel
     ProxyLabel.replace('$CURRENCY', get_localeconv()['currency_symbol'])
Example #9
0
    def format(self, symbol=True, precision=None):
        value = decimal.Decimal(self)

        conv = get_localeconv()

        # Grouping (eg thousand separator) of integer part
        groups = conv.get('mon_grouping', [])[:]
        groups.reverse()
        if groups:
            group = groups.pop()
        else:
            group = 3

        intparts = []

        # We're iterating over every character in the integer part
        # make sure to remove the negative sign, it'll be added later
        intpart = str(int(abs(value)))

        while True:
            if not intpart:
                break

            s = intpart[-group:]
            intparts.insert(0, s)
            intpart = intpart[:-group]
            if not groups:
                continue

            last = groups.pop()
            # if 0 reuse last one, see struct lconv in locale.h
            if last != 0:
                group = last

        # Add the sign, and the list of decmial parts, which now are grouped
        # properly and can be joined by mon_thousand_sep
        if value > 0:
            sign = conv.get('positive_sign', '')
        elif value < 0:
            sign = conv.get('negative_sign', '-')
        else:
            sign = ''
        currency = sign + conv.get('mon_thousands_sep', '.').join(intparts)

        # Only add decimal part if it has one, is this correct?
        if precision is not None or value % 1 != 0:
            # Pythons string formatting can't handle %.127f
            # 127 is the default value from glibc/python
            if precision:
                frac_digits = precision
            else:
                frac_digits = conv.get('frac_digits', 2)
                if frac_digits == 127:
                    frac_digits = 2

            format = '%%.%sf' % (frac_digits + 1)
            dec_part = (format % value)[-(frac_digits + 1):-1]

            mon_decimal_point = conv.get('mon_decimal_point', '.')
            currency += mon_decimal_point + dec_part

        # If requested include currency symbol
        currency_symbol = conv.get('currency_symbol', '')
        if currency_symbol and symbol:
            if value > 0:
                cs_precedes = conv.get('p_cs_precedes', 1)
                sep_by_space = conv.get('p_sep_by_space', 1)
            else:
                cs_precedes = conv.get('n_cs_precedes', 1)
                sep_by_space = conv.get('n_sep_by_space', 1)

            if sep_by_space:
                space = ' '
            else:
                space = ''
            if cs_precedes:
                currency = currency_symbol + space + currency
            else:
                currency = currency + space + currency_symbol

        return currency
Example #10
0
    def format(self, symbol=True, precision=None):
        value = decimal.Decimal(self)

        conv = get_localeconv()

        # Grouping (eg thousand separator) of integer part
        groups = conv.get("mon_grouping", [])[:]
        groups.reverse()
        if groups:
            group = groups.pop()
        else:
            group = 3

        intparts = []

        # We're iterating over every character in the integer part
        # make sure to remove the negative sign, it'll be added later
        intpart = str(int(abs(value)))

        while True:
            if not intpart:
                break

            s = intpart[-group:]
            intparts.insert(0, s)
            intpart = intpart[:-group]
            if not groups:
                continue

            last = groups.pop()
            # if 0 reuse last one, see struct lconv in locale.h
            if last != 0:
                group = last

        # Add the sign, and the list of decmial parts, which now are grouped
        # properly and can be joined by mon_thousand_sep
        if value > 0:
            sign = conv.get("positive_sign", "")
        elif value < 0:
            sign = conv.get("negative_sign", "-")
        else:
            sign = ""
        currency = sign + conv.get("mon_thousands_sep", ".").join(intparts)

        # Only add decimal part if it has one, is this correct?
        if precision is not None or value % 1 != 0:
            # Pythons string formatting can't handle %.127f
            # 127 is the default value from glibc/python
            if precision:
                frac_digits = precision
            else:
                frac_digits = conv.get("frac_digits", 2)
                if frac_digits == 127:
                    frac_digits = 2

            format = "%%.%sf" % (frac_digits + 1)
            dec_part = (format % value)[-(frac_digits + 1) : -1]

            mon_decimal_point = conv.get("mon_decimal_point", ".")
            currency += mon_decimal_point + dec_part

        # If requested include currency symbol
        currency_symbol = conv.get("currency_symbol", "")
        if currency_symbol and symbol:
            if value > 0:
                cs_precedes = conv.get("p_cs_precedes", 1)
                sep_by_space = conv.get("p_sep_by_space", 1)
            else:
                cs_precedes = conv.get("n_cs_precedes", 1)
                sep_by_space = conv.get("n_sep_by_space", 1)

            if sep_by_space:
                space = " "
            else:
                space = ""
            if cs_precedes:
                currency = currency_symbol + space + currency
            else:
                currency = currency + space + currency_symbol

        return currency