Example #1
0
    def calc_human_value(self, raw_value):
        # TODO: handle offset
        locale.setlocale(locale.LC_ALL, "")

        if isinstance(raw_value, str):
            enumeration_strings = self.enumeration_strings()
            if len(enumeration_strings) > 0:
                try:
                    index = enumeration_strings.index(raw_value)
                except ValueError:
                    enumeration_strings = self.enumeration_strings(
                        include_values=True)
                    if len(enumeration_strings) > 0:
                        try:
                            index = enumeration_strings.index(raw_value)
                        except ValueError:
                            index = int(raw_value)

                value = index
            else:
                value = decimal.Decimal(locale.delocalize(raw_value))
        else:
            value = raw_value

        if value is not None:
            value = self.from_human(value)

        return value
Example #2
0
 def get_value(self):
     txt_value = self.widget.get_text()
     if txt_value:
         try:
             return Decimal(locale.delocalize(txt_value))
         except decimal.InvalidOperation:
             pass
     return None
Example #3
0
 def value(self):
     text = self.get_text()
     if text:
         try:
             return self.convert(locale.delocalize(text, self.monetary))
         except ValueError:
             pass
     return None
Example #4
0
    def _read_pasted_text(text):
        """
        Parses a tab separated CSV text table.

        Args:
            text (str): a CSV formatted table
        Returns:
            a list of rows
        """
        with io.StringIO(text) as input_stream:
            reader = csv.reader(input_stream, delimiter="\t", quotechar="'")
            rows = list()
            for row in reader:
                rows.append([locale.delocalize(element) for element in row])
            return rows
Example #5
0
 def do_insert_text(self, new_text, length, position):
     buffer_ = self.get_buffer()
     text = self.get_buffer().get_text()
     text = text[:position] + new_text + text[position:]
     value = None
     if text not in ['-', self.__decimal_point, self.__thousands_sep]:
         try:
             value = self.convert(locale.delocalize(text, self.monetary))
         except ValueError:
             return position
     if (value and self.__digits is not None
             and round(value, self.__digits) != value):
         return position
     buffer_.insert_text(position, new_text, len(new_text))
     return position + len(new_text)
Example #6
0
 def _can_insert_text(self, entry, new_text, start_pos, end_pos=None):
     value = entry.get_text()
     if end_pos is None:
         end_pos = start_pos
     new_value = value[:start_pos] + new_text + value[end_pos:]
     if new_value not in {'-', self.__decimal_point, self.__thousands_sep}:
         try:
             value = self.convert(
                 locale.delocalize(new_value, self.monetary))
         except ValueError:
             return False
         if (value and self.digits is not None
                 and round(value, self.digits[1]) != value):
             return False
     return True
Example #7
0
def to_int_or_none(s):
    if s is None:
        return None

    if isinstance(s, str) and len(s) == 0:
        return None

    if isinstance(s, str):
        s = locale.delocalize(s)

    try:
        result = int(s)
    except ValueError as e:
        raise ValueError("Invalid number: {}".format(repr(s))) from e

    return result
Example #8
0
def to_decimal_or_none(s):
    if s is None:
        return None

    if isinstance(s, str) and len(s) == 0:
        return None

    if isinstance(s, str):
        s = locale.delocalize(s)

    try:
        result = decimal.Decimal(s)
    except decimal.InvalidOperation as e:
        raise ValueError("Invalid number: {}".format(repr(s))) from e

    return result
Example #9
0
    def __init__(self, quantity: Union[str, Decimal], currency: str = '€'):
        """ 
        Args
            'quantity' -- amount of money as string or Decimal
            'currency' -- symbol of the corresponding currency
        """

        if isinstance(quantity, str):
            self._quantity = Decimal(locale.delocalize(quantity))
        elif isinstance(quantity, Decimal):
            self._quantity = quantity
        else:
            raise (ValueError)

        if currency not in CURRENCY_MAP:
            raise InvalidCurrencyError(currency)
        self._currency = currency
Example #10
0
 def import_csv(self, fname, fields):
     # TODO: make it works with references
     skip = self.csv_skip.get_value_as_int()
     encoding = self.get_encoding()
     locale_format = self.csv_locale.get_active()
     try:
         reader = csv.reader(open(fname, 'r', encoding=encoding),
                             quotechar=self.get_quotechar(),
                             delimiter=self.get_delimiter())
         data = []
         for i, line in enumerate(reader):
             if i < skip or not line:
                 continue
             row = []
             for field, val in zip(fields, line):
                 if locale_format and val:
                     type_ = self.fields_data[field]['type']
                     if type_ in ['integer', 'biginteger']:
                         val = locale.atoi(val)
                     elif type_ == 'float':
                         val = locale.atof(val)
                     elif type_ == 'numeric':
                         val = Decimal(locale.delocalize(val))
                     elif type_ in ['date', 'datetime']:
                         val = date_parse(val, common.date_format())
                     elif type_ == 'binary':
                         val = base64.b64decode(val)
                 row.append(val)
             data.append(row)
     except (IOError, UnicodeDecodeError, csv.Error) as exception:
         common.warning(str(exception), _("Import failed"))
         return
     try:
         count = RPCExecute('model',
                            self.model,
                            'import_data',
                            fields,
                            data,
                            context=self.context)
     except RPCException:
         return
     if count == 1:
         common.message(_('%d record imported.') % count)
     else:
         common.message(_('%d records imported.') % count)
Example #11
0
 def convert(self, value):
     try:
         return Decimal(locale.delocalize(value))
     except decimal.InvalidOperation:
         return self._default
#!/usr/bin/env python3
#
# Copyright 2007 Doug Hellmann.
#
"""
"""

#end_pymotw_header
import locale

sample_locales = [
    ('USA', 'en_US'),
    ('France', 'fr_FR'),
    ('Spain', 'es_ES'),
    ('Portugal', 'pt_PT'),
    ('Poland', 'pl_PL'),
]

for name, loc in sample_locales:
    locale.setlocale(locale.LC_ALL, loc)
    localized = locale.format_string('%0.2f', 123456.78, grouping=True)
    delocalized = locale.delocalize(localized)
    print('{:>10}: {:>10}  {:>10}'.format(
        name,
        localized,
        delocalized,
    ))
Example #13
0
 def _test_delocalize(self, value, out):
     self.assertEqual(locale.delocalize(value), out)
Example #14
0
 def convert_numeric():
     factor = Decimal(field.get('factor', 1))
     try:
         return Decimal(locale.delocalize(value)) / factor
     except (decimal.InvalidOperation, AttributeError):
         return
# locale_delocalize.py

import locale

sample_locales = [
    ('USA', 'en_US'),
    ('Francia', 'fr_FR'),
    ('Spagna', 'es_ES'),
    ('Portogallo', 'pt_PT'),
    ('Polonia', 'pl_PL'),
]

for name, loc in sample_locales:
    locale.setlocale(locale.LC_ALL, loc)
    localized = locale.format('%0.2f', 123456.78, grouping=True)
    delocalized = locale.delocalize(localized)
    print('{:>10}: {:>10}  {:>10}'.format(
        name,
        localized,
        delocalized,
    ))
def __string_to_decimal_with_locale__(string):
    return Decimal(delocalize(string))
Example #17
0
def desformatar_moeda(valor_str, localizacao='pt_BR.utf8'):
    locale.setlocale(locale.LC_ALL, localizacao)
    return locale.delocalize(valor_str)
Example #18
0
 def convert(self, value):
     try:
         return Decimal(
             locale.delocalize(value, self.attrs.get('monetary', False)))
     except decimal.InvalidOperation:
         return self._default
Example #19
0
 def update_event(self, inp=-1):
     self.set_output_val(0, locale.delocalize(self.input(0)))
Example #20
0
 def convert(self, value):
     try:
         return int(
             locale.delocalize(value, self.attrs.get('monetary', False)))
     except ValueError:
         return self._default
Example #21
0
 def _test_delocalize(self, value, out):
     self.assertEqual(locale.delocalize(value), out)
Example #22
0
def format_value_back(value):
    return float(re.sub(r'[^0-9.]', '', locale.delocalize(value)))