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
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
def value(self): text = self.get_text() if text: try: return self.convert(locale.delocalize(text, self.monetary)) except ValueError: pass return None
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
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)
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
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
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
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
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)
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, ))
def _test_delocalize(self, value, out): self.assertEqual(locale.delocalize(value), out)
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))
def desformatar_moeda(valor_str, localizacao='pt_BR.utf8'): locale.setlocale(locale.LC_ALL, localizacao) return locale.delocalize(valor_str)
def convert(self, value): try: return Decimal( locale.delocalize(value, self.attrs.get('monetary', False))) except decimal.InvalidOperation: return self._default
def update_event(self, inp=-1): self.set_output_val(0, locale.delocalize(self.input(0)))
def convert(self, value): try: return int( locale.delocalize(value, self.attrs.get('monetary', False))) except ValueError: return self._default
def format_value_back(value): return float(re.sub(r'[^0-9.]', '', locale.delocalize(value)))