def _updateText(self): text = self.text() if text: src_text = text if not self.hasFocus() or self.isReadOnly(): try: if self._decimals: text = locale.format("%%.%df" % self._decimals, float(text), grouping=True) else: text = locale.format("%d", int(text), grouping=True) except ValueError: return if self._decimals: # Strip empty fraction dp = locale.localeconv()['decimal_point'] text = text.rstrip('0').rstrip(dp) else: ts = locale.localeconv()['thousands_sep'] if ts == '.': text = text.replace('.', ',') if src_text != text: super().setText(text)
def _formatSciNotation(self, s): # transform 1e+004 into 1e4, for example if self._useLocale: decimal_point = locale.localeconv()["decimal_point"] positive_sign = locale.localeconv()["positive_sign"] else: decimal_point = "." positive_sign = "+" tup = "{0:.2e}".format(float(s)).split("e") try: significand = tup[0].rstrip("0").rstrip(decimal_point) significand = "{0:.2f}".format(float(significand)) sign = tup[1][0].replace(positive_sign, "") exponent = tup[1][1:].lstrip("0") # if significand == '1': # reformat 1x10^y as 10^y # significand = '' if exponent: exponent = r"10^{%s%s}" % (sign, exponent) if significand and exponent: return r"$%s{\times}%s$" % (significand, exponent) else: return r"$%s%s$" % (significand, exponent) except IndexError: return s
def getUserLocale(localeCode=''): # get system localeconv and reset system back to default import locale conv = None if sys.platform == "darwin" and not localeCode: # possibly this MacOS bug: http://bugs.python.org/issue18378 # macOS won't provide right default code for english-european culture combinations localeQueryResult = subprocess.getstatusoutput("defaults read -g AppleLocale") # MacOS only if localeQueryResult[0] == 0 and '_' in localeQueryResult[1]: # successful localeCode = localeQueryResult[1] try: locale.setlocale(locale.LC_ALL, _STR_8BIT(localeCode)) # str needed for 3to2 2.7 python to work conv = locale.localeconv() except locale.Error: if sys.platform == "darwin": # possibly this MacOS bug: http://bugs.python.org/issue18378 # the fix to this bug will loose the monetary/number configuration with en_BE, en_FR, etc # so use this alternative which gets the right culture code for numbers even if english default language localeCulture = '-' + localeCode[3:] # find culture (for any language) in available locales for availableLocale in availableLocales(): if len(availableLocale) >= 5 and localeCulture in availableLocale: try: locale.setlocale(locale.LC_ALL, availableLocale.replace('-','_')) conv = locale.localeconv() # should get monetary and numeric codes break except locale.Error: pass # this one didn't work locale.setlocale(locale.LC_ALL, _STR_8BIT('C')) # str needed for 3to2 2.7 python to work if conv is None: # some other issue prevents getting culture code, use 'C' defaults (no thousands sep, no currency, etc) conv = locale.localeconv() # use 'C' environment, e.g., en_US return conv
def _formatSciNotation(self, s): # transform 1e+004 into 1e4, for example if self._useLocale: decimal_point = locale.localeconv()['decimal_point'] positive_sign = locale.localeconv()['positive_sign'] else: decimal_point = '.' positive_sign = '+' tup = '{0:.2e}'.format(float(s)).split('e') try: significand = tup[0].rstrip('0').rstrip(decimal_point) significand = '{0:.2f}'.format(float(significand)) sign = tup[1][0].replace(positive_sign, '') exponent = tup[1][1:].lstrip('0') # if significand == '1': # reformat 1x10^y as 10^y # significand = '' if exponent: exponent = r'10^{%s%s}' % (sign, exponent) if significand and exponent: return r'$%s{\times}%s$' % (significand, exponent) else: return r'$%s%s$' % (significand, exponent) except IndexError: return s
def _formatSciNotation(self, s): # transform 1e+004 into 1e4, for example if self._useLocale: decimal_point = locale.localeconv()['decimal_point'] positive = locale.localeconv()['positive_sign'] else: decimal_point = '.' positive_sign = '+' tup = s.split('e') try: significand = tup[0].rstrip('0').rstrip(decimal_point) sign = tup[1][0].replace(positive_sign, '') exponent = tup[1][1:].lstrip('0') if self._useMathText or self._usetex: if significand == '1': # reformat 1x10^y as 10^y significand = '' if exponent: exponent = '10^{%s%s}'%(sign, exponent) if significand and exponent: return r'%s{\times}%s'%(significand, exponent) else: return r'%s%s'%(significand, exponent) else: s = ('%se%s%s' %(significand, sign, exponent)).rstrip('e') return s except IndexError: return s
def formatFields(field, data): try: if field.name == 'status': text = Statuses[data] elif field.type == Type.BigInt: text = locale.format("%d", int(data), grouping=True) elif field.type == Type.Money: text = locale.format("%.2f", float(data), grouping=True) dp = locale.localeconv()['decimal_point'] text = text.rstrip('0').rstrip(dp) elif field.type == Type.Value: text = locale.format("%.3f", float(data), grouping=True) dp = locale.localeconv()['decimal_point'] text = text.rstrip('0').rstrip(dp) elif field.type == Type.Date: date = QtCore.QDate.fromString(data, Qt.ISODate) text = date.toString(Qt.SystemLocaleShortDate) elif field.type == Type.DateTime: date = QtCore.QDateTime.fromString(data, Qt.ISODate) # Timestamp in DB stored in UTC date.setTimeSpec(Qt.UTC) date = date.toLocalTime() text = date.toString(Qt.SystemLocaleShortDate) else: return data except (ValueError, TypeError): return data return text
def load_lang(self, cr, uid, lang, lang_name=None): # create the language with locale information fail = True iso_lang = tools.get_iso_codes(lang) for ln in tools.get_locales(lang): try: locale.setlocale(locale.LC_ALL, str(ln)) fail = False break except locale.Error: continue if fail: lc = locale.getdefaultlocale()[0] msg = 'Unable to get information for locale %s. Information from the default locale (%s) have been used.' _logger.warning(msg, lang, lc) if not lang_name: lang_name = tools.ALL_LANGUAGES.get(lang, lang) def fix_xa0(s): """Fix badly-encoded non-breaking space Unicode character from locale.localeconv(), coercing to utf-8, as some platform seem to output localeconv() in their system encoding, e.g. Windows-1252""" if s == '\xa0': return '\xc2\xa0' return s def fix_datetime_format(format): """Python's strftime supports only the format directives that are available on the platform's libc, so in order to be 100% cross-platform we map to the directives required by the C standard (1989 version), always available on platforms with a C standard implementation.""" # For some locales, nl_langinfo returns a D_FMT/T_FMT that contains # unsupported '%-' patterns, e.g. for cs_CZ format = format.replace('%-', '%') for pattern, replacement in tools.DATETIME_FORMATS_MAP.iteritems(): format = format.replace(pattern, replacement) return str(format) lang_info = { 'code': lang, 'iso_code': iso_lang, 'name': lang_name, 'translatable': 1, 'date_format' : fix_datetime_format(locale.nl_langinfo(locale.D_FMT)), 'time_format' : fix_datetime_format(locale.nl_langinfo(locale.T_FMT)), 'decimal_point' : fix_xa0(str(locale.localeconv()['decimal_point'])), 'thousands_sep' : fix_xa0(str(locale.localeconv()['thousands_sep'])), 'position': 'before' if locale.nl_langinfo(locale.CRNCYSTR)[0] == '-' else 'after' } lang_id = False try: lang_id = self.create(cr, uid, lang_info) finally: tools.resetlocale() return lang_id
def __init__(self, **config): GenPollUrl.__init__(self, **config) self.add_defaults(BitcoinTicker.defaults) # set up USD as the default if no locale is set if self.currency == "": locale.setlocale(locale.LC_MONETARY, "en_US.UTF-8") self.currency = locale.localeconv()['int_curr_symbol'].strip() self.symbol = locale.localeconv()['currency_symbol']
def checkAndFixLocaleDecimal_point(verbose=False): if locale.localeconv()["decimal_point"] == ",": if verbose: print("Found locale decimal_point ',' " "and change it to: decimal point '.'") try: locale.localeconv()["decimal_point"] locale.setlocale(locale.LC_NUMERIC, "C") except Exception as e: print(e) print("cannot set locale to decimal point")
def format_cur_code(cur_code): if cur_code == "USD": locale.setlocale(locale.LC_ALL, 'en_US.utf8') return locale.localeconv()['currency_symbol'] elif cur_code == "GBP": locale.setlocale(locale.LC_ALL, 'en_GB.utf8') return locale.localeconv()['currency_symbol'] else: return cur_code end
def set_value( self, value ): val = value try: val = str( locale.format( "%f", float( val ) ).rstrip( "0" ) ) if val[-1] == locale.localeconv()["decimal_point"]: val = val.rstrip( locale.localeconv()["decimal_point"] ) except: value = "Error" self.delete() self.displayOperand( str( val ) ) self.preset_value = value
def __init__(self, dot='', symbol=''): import locale locale.setlocale(locale.LC_ALL, "") if not dot: self.dot = locale.localeconv()['decimal_point'] else: self.dot = dot if not symbol: self.symbol = locale.localeconv()['currency_symbol'] else: self.symbol = symbol
def validate(self, input_, pos): input_ = input_.lstrip() if len(input_) == 0: return QValidator.Intermediate, input_, pos lastWasDigit = False decPointFound = False decDigitCnt = 0 value = '0' ts = [locale.localeconv()['thousands_sep'], ] if ts[0] == chr(0xA0): ts.append(' ') dp = [locale.localeconv()['decimal_point'], ] if dp[0] == ',' and '.' not in ts: dp.append('.') for c in input_: if c.isdigit(): if decPointFound and self.decimals() > 0: if decDigitCnt < self.decimals(): decDigitCnt += 1 else: return QValidator.Invalid, input_, pos value = value + c lastWasDigit = True else: if c in dp and self.decimals() != 0: if decPointFound: return QValidator.Invalid, input_, pos else: value += '.' decPointFound = True elif c in ts: if not lastWasDigit or decPointFound: return QValidator.Invalid, input_, pos elif c == '-' and value == '0': if self.bottom() > 0: return QValidator.Invalid, input_, pos value = '-0' else: return QValidator.Invalid, input_, pos lastWasDigit = False try: val = float(value) except ValueError: return QValidator.Invalid, input_, pos if self.bottom() > val or val > self.top(): return QValidator.Invalid, input_, pos return QValidator.Acceptable, input_, pos
def load_lang(self, cr, uid, lang, lang_name=None): # create the language with locale information fail = True iso_lang = tools.get_iso_codes(lang) for ln in tools.get_locales(lang): try: locale.setlocale(locale.LC_ALL, str(ln)) fail = False break except locale.Error: continue if fail: lc = locale.getdefaultlocale()[0] msg = "Unable to get information for locale %s. Information from the default locale (%s) have been used." _logger.warning(msg, lang, lc) if not lang_name: lang_name = tools.ALL_LANGUAGES.get(lang, lang) def fix_xa0(s): """Fix badly-encoded non-breaking space Unicode character from locale.localeconv(), coercing to utf-8, as some platform seem to output localeconv() in their system encoding, e.g. Windows-1252""" if s == "\xa0": return "\xc2\xa0" return s def fix_datetime_format(format): """Python's strftime supports only the format directives that are available on the platform's libc, so in order to be 100% cross-platform we map to the directives required by the C standard (1989 version), always available on platforms with a C standard implementation.""" for pattern, replacement in tools.DATETIME_FORMATS_MAP.iteritems(): format = format.replace(pattern, replacement) return str(format) lang_info = { "code": lang, "iso_code": iso_lang, "name": lang_name, "translatable": 1, "date_format": fix_datetime_format(locale.nl_langinfo(locale.D_FMT)), "time_format": fix_datetime_format(locale.nl_langinfo(locale.T_FMT)), "decimal_point": fix_xa0(str(locale.localeconv()["decimal_point"])), "thousands_sep": fix_xa0(str(locale.localeconv()["thousands_sep"])), } lang_id = False try: lang_id = self.create(cr, uid, lang_info) finally: tools.resetlocale() return lang_id
def checkAndFixLocaleDecimal_point(verbose=False): """ """ if locale.localeconv()['decimal_point'] == ',': if verbose: print("Found locale decimal_point ',' " "and change it to: decimal point '.'") try: locale.localeconv()['decimal_point'] locale.setlocale(locale.LC_NUMERIC, 'C') except Exception as e: print(e) print('cannot set locale to decimal point')
def data(self, index, role=Qt.DisplayRole): if role == Qt.DisplayRole: # Localize values data = super(CollectionModel, self).data(index, role) field = self.fields.fields[index.column()] try: if field.name == 'status': text = Statuses[data] elif field.type == Type.BigInt: text = locale.format("%d", int(data), grouping=True) elif field.type == Type.Money: text = locale.format("%.2f", float(data), grouping=True) dp = locale.localeconv()['decimal_point'] text = text.rstrip('0').rstrip(dp) elif field.type == Type.Value: text = locale.format("%.3f", float(data), grouping=True) dp = locale.localeconv()['decimal_point'] text = text.rstrip('0').rstrip(dp) elif field.type == Type.Date: date = QtCore.QDate.fromString(data, Qt.ISODate) text = date.toString(Qt.SystemLocaleShortDate) elif field.type == Type.Image or field.type == Type.EdgeImage: if data: image, fileName = self.getImage(data) return image else: return None elif field.type == Type.PreviewImage: if data: return self.getPreviewImage(data) else: return None elif field.type == Type.DateTime: date = QtCore.QDateTime.fromString(data, Qt.ISODate) # Timestamp in DB stored in UTC date.setTimeSpec(Qt.UTC) date = date.toLocalTime() text = date.toString(Qt.SystemLocaleShortDate) else: return data except (ValueError, TypeError): return data return text elif role == Qt.UserRole: return super(CollectionModel, self).data(index, Qt.DisplayRole) elif role == Qt.TextAlignmentRole: field = self.fields.fields[index.column()] if field.type == Type.BigInt: return Qt.AlignRight | Qt.AlignVCenter return super(CollectionModel, self).data(index, role)
def text(self): text = super(_DoubleEdit, self).text() # First, get rid of the grouping ts = locale.localeconv()['thousands_sep'] if ts: text = text.replace(ts, '') if ts == chr(0xA0): text = text.replace(' ', '') # next, replace the decimal point with a dot if self._decimals: dp = locale.localeconv()['decimal_point'] if dp: text = text.replace(dp, '.') return text
def get_windows_number_formats(): ans = getattr(get_windows_number_formats, 'ans', None) if ans is None: winutil = plugins['winutil'][0] localeconv = getattr(winutil, 'localeconv', None) if localeconv is not None: d = localeconv() thousands_sep, decimal_point = d['thousands_sep'], d['decimal_point'] else: from locale import localeconv d = localeconv() thousands_sep, decimal_point = d['thousands_sep'].decode('mbcs'), d['decimal_point'].decode('mbcs') ans = get_windows_number_formats.ans = thousands_sep, decimal_point return ans
def word(value, digits=2): """ Converts a large number to a formatted number containing the textual suffix for that number. :param value: number >>> print word(1) 1 >>> print word(123456789) 123.46 million """ convention = locale.localeconv() decimal_point = convention["decimal_point"] prefix = value < 0 and u"-" or u"" value = abs(long(value)) if value < 1000: return u"".join([prefix, _format(value, digits).rstrip("%s0" % (decimal_point,))]) for base, suffix in enumerate(LARGE_NUMBER_SUFFIX): exp = (base + 2) * 3 power = 10 ** exp if value < power: value = value / float(10 ** (exp - 3)) return u"".join([prefix, _format(value, digits).rstrip("%s0" % (decimal_point,)), u" ", suffix]) raise OverflowError
def get_pay_link(self): shop = lfs_get_object_or_404(Shop, pk=1) current_site = Site.objects.get(id=settings.SITE_ID) conv = locale.localeconv() default_currency = conv['int_curr_symbol'] info = { "cmd": "_xclick", "upload": "1", "business": settings.PAYPAL_RECEIVER_EMAIL, "currency_code": default_currency, "notify_url": "http://" + current_site.domain + reverse('paypal-ipn'), "return": "http://" + current_site.domain + reverse('paypal-pdt'), "first_name": self.order.invoice_address.firstname, "last_name": self.order.invoice_address.lastname, "address1": self.order.invoice_address.line1, "address2": self.order.invoice_address.line2, "city": self.order.invoice_address.city, "state": self.order.invoice_address.state, "zip": self.order.invoice_address.zip_code, "no_shipping": "1", "custom": self.order.uuid, "invoice": self.order.uuid, "item_name": shop.shop_owner, "amount": "%.2f" % (self.order.price - self.order.tax), "tax": "%.2f" % self.order.tax, } parameters = "&".join(["%s=%s" % (k, v) for (k, v) in info.items()]) if getattr(settings, 'PAYPAL_DEBUG', settings.DEBUG): url = SANDBOX_POSTBACK_ENDPOINT + "?" + parameters else: url = POSTBACK_ENDPOINT + "?" + parameters return url
def test_float_with_comma(self): # set locale to something that doesn't use '.' for the decimal point # float must not accept the locale specific decimal point but # it still has to accept the normal python syntac import locale if not locale.localeconv()['decimal_point'] == ',': return self.assertEqual(float(" 3.14 "), 3.14) self.assertEqual(float("+3.14 "), 3.14) self.assertEqual(float("-3.14 "), -3.14) self.assertEqual(float(".14 "), .14) self.assertEqual(float("3. "), 3.0) self.assertEqual(float("3.e3 "), 3000.0) self.assertEqual(float("3.2e3 "), 3200.0) self.assertEqual(float("2.5e-1 "), 0.25) self.assertEqual(float("5e-1"), 0.5) self.assertRaises(ValueError, float, " 3,14 ") self.assertRaises(ValueError, float, " +3,14 ") self.assertRaises(ValueError, float, " -3,14 ") self.assertRaises(ValueError, float, " 0x3.1 ") self.assertRaises(ValueError, float, " -0x3.p-1 ") self.assertRaises(ValueError, float, " +0x3.p-1 ") self.assertEqual(float(" 25.e-1 "), 2.5) self.assertEqual(test_support.fcmp(float(" .25e-1 "), .025), 0)
def _lang_data_get(self, cr, uid, lang_id, monetary=False): conv = localeconv() lang_obj = self.browse(cr, uid, lang_id) thousands_sep = lang_obj.thousands_sep or conv[monetary and "mon_thousands_sep" or "thousands_sep"] decimal_point = lang_obj.decimal_point grouping = lang_obj.grouping return grouping, thousands_sep, decimal_point
def parse_decimal_number(number_string, lang): """Parses a decimal number string into a float. Can also handle thousands separators. @type number_string: unicode @param number_string: The decimal number as a string. @type lang: str @param lang: The locale of the format. @rtype: float @return: The parsed number. @raise ValueError: If the string is not a valid decimal number. """ orig_locale = locale.getlocale(locale.LC_ALL) locale.setlocale(locale.LC_ALL, lang) thousands_sep = locale.localeconv()['mon_thousands_sep'] if lang == 'de_CH': # Buggy Swiss locale. locale.setlocale(locale.LC_ALL, 'en_US') thousands_sep = "'" try: return locale.atof(number_string.replace(thousands_sep, '')) finally: locale.setlocale(locale.LC_ALL, orig_locale)
def currency(value): try: locale.setlocale(locale.LC_ALL,'en_IN.UTF-8') except: locale.setlocale(locale.LC_ALL,'') loc = locale.localeconv() return locale.currency(value, loc['currency_symbol'], grouping=True)
def sig_insert_text(self, entry, new_text, new_text_length, position): if not self.record: entry.stop_emission('insert-text') return value = entry.get_text() position = entry.get_position() new_value = value[:position] + new_text + value[position:] decimal_point = locale.localeconv()['decimal_point'] if new_value in ('-', decimal_point): return digits = self.field.digits(self.record) try: locale.atof(new_value) except ValueError: entry.stop_emission('insert-text') return new_int = new_value new_decimal = '' if decimal_point in new_value: new_int, new_decimal = new_value.rsplit(decimal_point, 1) if len(new_int) > digits[0] \ or len(new_decimal) > digits[1]: entry.stop_emission('insert-text')
def __init__(self, *args, **kwargs): # Use local conventions for decimal point and grouping lc = locale.localeconv() kwargs['useFixedWidthFont'] = False kwargs['groupChar'] = lc['mon_thousands_sep'] or ',' kwargs['decimalChar'] = lc['decimal_point'] or '.' # fix non-breaking space 0xa0 thousands sep in French_France.1252 (win) for k in ('groupChar', 'decimalChar'): # on python2, convert everything to unicode if isinstance(kwargs[k], str) and hasattr(str, "decode"): kwargs[k] = kwargs[k].decode("latin1", "replace") mask = kwargs['mask'] del kwargs['mask'] if '.' not in mask: kwargs['fractionWidth'] = 0 kwargs['integerWidth'] = mask.count("#") else: kwargs['fractionWidth'] = mask[mask.index("."):].count("#") kwargs['integerWidth'] = mask[:mask.index(".")].count("#") kwargs['allowNone'] = True kwargs['autoSize'] = False #allowNegative = True, #useParensForNegatives = False, #groupDigits = False, #min = None, #max = None, masked.NumCtrl.__init__(self, *args, **kwargs)
def main(): locale.setlocale(locale.LC_ALL, '') cur = locale.localeconv()['int_curr_symbol'][:3] or 'GBP' parser = argparse.ArgumentParser( description='Monitor BullionVault Exchange') parser.add_argument('-t', '--test', action='store_true', help='Get and display the current price twice \ (ignores -q)') parser.add_argument('-s', '--save', help='Save the price to <SAVE>') parser.add_argument('-q', '--quiet', action='store_true', help='Do not display the price') parser.add_argument('-c', '--currency', default=cur, help='Currency in which to retrieve price') args = parser.parse_args() mon = BullionVaultMonitor(currency=args.currency) if args.test: mon.price.printstate() sleep(mon.updatePeriod + 1) mon.price.printstate() return if args.save: store = price.Store(args.save) store.save(mon.price) store.close() if not args.quiet: mon.price.printstate()
def locale_convert(val, func, group): """\ Attempt to convert a string to a number, first converting the decimal place character if needed. Then, if the conversion was not possible (i.e. it is not a number), run it through strxfrm to make the work sorting as requested, possibly grouping first. """ # Format the number so that the conversion function can interpret it. radix = localeconv()['decimal_point'] s = val.replace(radix, '.') if radix != '.' else val # Perform the conversion t = func[0](s) # Return the number or transformed string. # If the input is identical to the output, then no conversion happened. # In this case, we don't want to return the function output because it # may have had characters modified from the above 'replace' call, # so we return the input. if group: if use_pyicu: xfrm = get_pyicu_transform(getlocale()) return xfrm(groupletters(val)) if not func[1](t) else t else: return strxfrm(groupletters(val)) if not func[1](t) else t else: if use_pyicu: xfrm = get_pyicu_transform(getlocale()) return xfrm(val) if not func[1](t) else t else: return strxfrm(val) if not func[1](t) else t
def getUserLocale(): # get system localeconv and reset system back to default import locale locale.setlocale(locale.LC_ALL, _STR_8BIT('')) # str needed for 3to2 2.7 python to work conv = locale.localeconv() locale.setlocale(locale.LC_ALL, _STR_8BIT('C')) # str needed for 3to2 2.7 python to work return conv
def get_locale_currency_symbol(): """Get currency symbol from locale """ import locale locale.setlocale(locale.LC_ALL, '') conv = locale.localeconv() return conv['currency_symbol']
def __init__(self, direction_label=True, degree_symbol='°', number_format='g', transform_precision=1e-8, dms=False, minute_symbol='′', second_symbol='″', seconds_number_format='g', auto_hide=True, decimal_point=None, cardinal_labels=None): """ Base class for simpler implementation of specialised formatters for latitude and longitude axes. """ self._direction_labels = direction_label self._degree_symbol = degree_symbol self._degrees_number_format = number_format self._transform_precision = transform_precision self._dms = dms self._minute_symbol = minute_symbol self._second_symbol = second_symbol self._seconds_num_format = seconds_number_format self._auto_hide = auto_hide self._auto_hide_degrees = False self._auto_hide_minutes = False self._precision = 5 # locator precision if (decimal_point is None and mpl.rcParams['axes.formatter.use_locale']): import locale decimal_point = locale.localeconv()["decimal_point"] if cardinal_labels is None: cardinal_labels = {} self._cardinal_labels = cardinal_labels self._decimal_point = decimal_point
def validate(self, input_, pos): input_ = input_.lstrip() if len(input_) == 0: return QValidator.Intermediate, input_, pos lastWasDigit = False value = '0' ts = [locale.localeconv()['thousands_sep'], ] if ts[0] == chr(0xA0): ts.append(' ') tss = (ts[0], ' ', chr(0xA0), '.', ',') for c in input_: if c.isdigit(): value = value + c lastWasDigit = True else: if c in tss: if not lastWasDigit: return QValidator.Invalid, input_, pos else: return QValidator.Invalid, input_, pos lastWasDigit = False try: val = int(value) except ValueError: return QValidator.Invalid, input_, pos if not lastWasDigit and len(input_) > 0 and input_[-1] not in ts: return QValidator.Invalid, input_, pos if self.bottom() > val or val > self.top(): return QValidator.Invalid, input_, pos return QValidator.Acceptable, input_, pos
def word(value, digits=2): ''' Converts a large number to a formatted number containing the textual suffix for that number. :param value: number >>> print word(1) 1 >>> print word(123456789) 123.46 million ''' convention = locale.localeconv() decimal_point = convention['decimal_point'] prefix = value < 0 and u'-' or u'' value = abs(long(value)) if value < 1000: return u''.join([ prefix, _format(value, digits).rstrip('%s0' % (decimal_point, )), ]) for base, suffix in enumerate(LARGE_NUMBER_SUFFIX): exp = (base + 2) * 3 power = 10**exp if value < power: value = value / float(10**(exp - 3)) return u''.join([ prefix, _format(value, digits).rstrip('%s0' % (decimal_point, )), u' ', suffix, ]) raise OverflowError
def get_paypal_link_for_order(order): """Creates paypal link for given order. """ shop = lfs_get_object_or_404(Shop, pk=1) current_site = Site.objects.get(id=settings.SITE_ID) conv = locale.localeconv() default_currency = conv['int_curr_symbol'] info = { "cmd": "_xclick", "upload": "1", "business": settings.PAYPAL_RECEIVER_EMAIL, "currency_code": default_currency, "notify_url": "http://" + current_site.domain + reverse('paypal-ipn'), "return": "http://" + current_site.domain + reverse('paypal-pdt'), "first_name": order.invoice_firstname, "last_name": order.invoice_lastname, "address1": order.invoice_line1, "address2": order.invoice_line2, "city": order.invoice_city, "state": order.invoice_state, "zip": order.invoice_code, "no_shipping": "1", "custom": order.uuid, "invoice": order.uuid, "item_name": shop.shop_owner, "amount": "%.2f" % (order.price - order.tax), "tax": "%.2f" % order.tax, } parameters = "&".join(["%s=%s" % (k, v) for (k, v) in info.items()]) if getattr(settings, 'PAYPAL_DEBUG', settings.DEBUG): url = SANDBOX_POSTBACK_ENDPOINT + "?" + parameters else: url = POSTBACK_ENDPOINT + "?" + parameters return url
def get_localeconv(): conv = locale.localeconv() monetary_locale = locale.getlocale(locale.LC_MONETARY) numeric_locale = locale.getlocale(locale.LC_NUMERIC) # Patching glibc's output # See http://sources.redhat.com/bugzilla/show_bug.cgi?id=1294 if monetary_locale[0] == 'pt_BR': conv['p_cs_precedes'] = 1 conv['p_sep_by_space'] = 1 # Since locale 'C' doesn't have any information on monetary and numeric # locale, use default en_US, so we can have formated numbers if not monetary_locale[0]: conv["negative_sign"] = '-' conv["currency_symbol"] = '$' conv['mon_thousands_sep'] = '' conv['mon_decimal_point'] = '.' conv['p_sep_by_space'] = 0 if not numeric_locale[0]: conv['decimal_point'] = '.' return conv
def format_satoshis(x, num_zeros=0, decimal_point=8, precision=None, is_diff=False, whitespaces=False): if x is None: return 'unknown' if precision is None: precision = decimal_point decimal_format = ".0" + str(precision) if precision > 0 else "" if is_diff: decimal_format = '+' + decimal_format result = ("{:" + decimal_format + "f}").format( x / pow(10, decimal_point)).rstrip('0') integer_part, fract_part = result.split(".") dp = localeconv()['decimal_point'] if len(fract_part) < num_zeros: fract_part += "0" * (num_zeros - len(fract_part)) result = integer_part + dp + fract_part if whitespaces: result += " " * (decimal_point - len(fract_part)) result = " " * (15 - len(result)) + result return result
def test_locale(self): try: oldloc = locale.setlocale(locale.LC_ALL) locale.setlocale(locale.LC_ALL, '') except locale.Error as err: self.skipTest("Cannot set locale: {}".format(err)) try: localeconv = locale.localeconv() sep = localeconv['thousands_sep'] point = localeconv['decimal_point'] grouping = localeconv['grouping'] text = format(123456789, "n") if grouping: self.assertIn(sep, text) self.assertEqual(text.replace(sep, ''), '123456789') text = format(1234.5, "n") if grouping: self.assertIn(sep, text) self.assertIn(point, text) self.assertEqual(text.replace(sep, ''), '1234' + point + '5') finally: locale.setlocale(locale.LC_ALL, oldloc)
def test_zh_TW_Big5(self): loc = "zh_TW.Big5" if BSD else "zh_TW.big5" if FREEBSD: currency_symbol = u'\uff2e\uff34\uff04' decimal_point = u'\uff0e' thousands_sep = u'\uff0c' date_str = u'\u661f\u671f\u56db 2\u6708' else: currency_symbol = u'NT$' decimal_point = u'.' thousands_sep = u',' if MACOS: date_str = u'\u9031\u56db 2\u6708' else: date_str = u'\u9031\u56db \u4e8c\u6708' self.set_locale(loc, "Big5") lc = locale.localeconv() self.assertLocaleEqual(lc['currency_symbol'], currency_symbol) self.assertLocaleEqual(lc['decimal_point'], decimal_point) self.assertLocaleEqual(lc['thousands_sep'], thousands_sep) self.assertLocaleEqual(time.strftime('%A %B', FEBRUARY), date_str)
def lookup_currency(locale_name): # pragma: no cover """ This is a helper to get information about a new currency. Start a python shell, import this function, and call it with a locale name that uses the currency. It'll print out the dictionary to copy/paste into the above data structure. To find valid locale names on your system, run "locale -a". If you don't see the locale you need, and you're on a Debian-based system, you can install a language-pack package that includes data for the language or country you need. E.g. "language-pack-ar" and "language-pack-ar-base" provide the data for all Arabic-speaking countries, or "language-pack-tr" and "language-pack-base-tr" for Turkish. So to lookup the data for US Dollars, you'd pass "en_US.utf8"; for Jordanian dinars, "ar_JO.utf8" """ import locale locale.setlocale(locale.LC_ALL, locale_name) conv = locale.localeconv() print(repr(conv))
def sig_insert_text(self, entry, new_text, new_text_length, position): value = entry.get_text() position = entry.get_position() new_value = value[:position] + new_text + value[position:] decimal_point = locale.localeconv()['decimal_point'] if new_value in ('-', decimal_point): return digits = self.digits() try: locale.atof(new_value) except ValueError: entry.stop_emission('insert-text') return new_int = new_value new_decimal = '' if decimal_point in new_value: new_int, new_decimal = new_value.rsplit(decimal_point, 1) if (len(new_int) > digits[0] or len(new_decimal) > digits[1]): entry.stop_emission('insert-text')
def _format(value, digits=None): if isinstance(value, basestring): value = locale.atof(value) number = long(value) convention = locale.localeconv() if digits is None: digits = convention['frac_digits'] partials = [] if digits == 0: number = long(round(value, 0)) else: fraction = str(round((value - number) * 10**digits)).split('.')[0] fraction = fraction[:digits] if len(fraction) < digits: fraction = fraction.ljust(digits, '0') if fraction: partials.append(fraction) partials.append(convention['decimal_point']) number = str(number) for x in xrange(len(number) + 3, 0, -3): partial = number[max(0, x - 3):x] if partial: partials.append(number[max(0, x - 3):x]) partials.append(convention['thousands_sep']) if partials[-1] == convention['thousands_sep']: partials = partials[:-1] partials.reverse() return ''.join(partials)
def currency(value): """ Format a value as currency according to locale. """ set_locale() if not value: value = 0 if hasattr(locale, "currency"): value = locale.currency(Decimal(value), grouping=True) if platform.system() == 'Windows': try: value = str(value, encoding='iso_8859_1') except TypeError: pass else: # based on locale.currency() in python >= 2.5 conv = locale.localeconv() value = [conv["currency_symbol"], conv["p_sep_by_space"] and " " or "", (("%%.%sf" % conv["frac_digits"]) % value).replace(".", conv["mon_decimal_point"])] if not conv["p_cs_precedes"]: value.reverse() value = "".join(value) return value
def _data_get(self, monetary=False): conv = locale.localeconv() thousands_sep = self.thousands_sep or conv[monetary and 'mon_thousands_sep' or 'thousands_sep'] decimal_point = self.decimal_point grouping = self.grouping return grouping, thousands_sep, decimal_point
def update_item_state(self, item): tx_hash = item.data(0, Qt.UserRole) status, conf = item.data(0, SortableTreeWidgetItem.DataRole) token_id = item.data(4, Qt.UserRole) delta = item.data(3, Qt.UserRole) try: validity = self.wallet.get_slp_token_info(tx_hash)['validity'] except KeyError: # Can happen if non-token tx (if burning tokens) validity = None try: tinfo = self.wallet.token_types[token_id] except KeyError: unktoken = True tokenname = _("%.4s... (unknown - right click to add)"%(token_id,)) deltastr = '%+d'%(delta,) else: if tinfo['decimals'] == '?': unktoken = True tokenname = _("%.4s... (unknown - right click to add)"%(token_id,)) deltastr = '%+d'%(delta,) else: unktoken = False tokenname=tinfo['name'] deltastr = format_satoshis_nofloat(delta, is_diff=True, decimal_point=tinfo['decimals'],) # right-pad so the decimal points line up # (note that because zeros are stripped, we have to locate decimal point here) dp = localeconv()['decimal_point'] d1,d2 = deltastr.rsplit(dp,1) deltastr += "\u2014"*(9-len(d2)) # \u2014 is long dash if unktoken and validity in (None,0,1): # If a token is not in our list of known token_ids, warn the user. icon=QIcon(":icons/warning.png") icontooltip = _("Unknown token ID") elif validity == 0: # For in-progress validation, always show gears regardless of confirmation status. icon=QIcon(":icons/unconfirmed.svg") icontooltip = _("ZSLP unvalidated") elif validity in (None,2,3): icon=QIcon(":icons/expired.svg") if validity is None: icontooltip = "non-ZSLP (tokens burned!)" else: icontooltip = "ZSLP invalid (tokens burned!)" elif validity == 4: icon=QIcon(":icons/expired.svg") icontooltip = "Bad NFT1 Parent" elif validity == 1: # For SLP valid known txes, show the confirmation status (gears, few-confirmations, or green check) icon = QIcon(":icons/" + TX_ICONS[status]) icontooltip = _("ZSLP valid; ") + str(conf) + " confirmation" + ("s" if conf != 1 else "") else: raise ValueError(validity) if unktoken: item.setForeground(3, QBrush(QColor("#888888"))) item.setForeground(4, QBrush(QColor("#888888"))) elif delta < 0: item.setForeground(3, QBrush(QColor("#BC1E1E"))) item.setIcon(0, icon) item.setToolTip(0, icontooltip) item.setText(4, tokenname) item.setText(3, deltastr)
def setUp(self): self.sep = locale.localeconv()['thousands_sep']
def _get_default_decimal_point(use_locale=None): """ Get decimal point symbol for current locale. Called externally. """ use_locale = _not_none(use_locale, rc['formatter.use_locale']) return locale.localeconv()['decimal_point'] if use_locale else '.'
def __log_locale_settings(message=None): _setlocale_categories = {} for category in 'LC_ALL LC_CTYPE LC_COLLATE LC_TIME LC_MONETARY LC_MESSAGES LC_NUMERIC'.split( ): try: _setlocale_categories[category] = getattr(locale, category) except: _log.warning('this OS does not have locale.%s', category) _getlocale_categories = {} for category in 'LC_CTYPE LC_COLLATE LC_TIME LC_MONETARY LC_MESSAGES LC_NUMERIC'.split( ): try: _getlocale_categories[category] = getattr(locale, category) except: pass if message is not None: _log.debug(message) _log.debug('current locale settings:') _log.debug('locale.getlocale(): %s' % str(locale.getlocale())) for category in _getlocale_categories.keys(): _log.debug( 'locale.getlocale(%s): %s' % (category, locale.getlocale(_getlocale_categories[category]))) for category in _setlocale_categories.keys(): _log.debug( '(locale.setlocale(%s): %s)' % (category, locale.setlocale(_setlocale_categories[category]))) try: _log.debug('locale.getdefaultlocale() - default (user) locale: %s' % str(locale.getdefaultlocale())) except ValueError: _log.exception('the OS locale setup seems faulty') _log.debug( 'encoding sanity check (also check "locale.nl_langinfo(CODESET)" below):' ) pref_loc_enc = locale.getpreferredencoding(do_setlocale=False) loc_enc = locale.getlocale()[1] py_str_enc = sys.getdefaultencoding() sys_fs_enc = sys.getfilesystemencoding() _log.debug('sys.getdefaultencoding(): [%s]' % py_str_enc) _log.debug('locale.getpreferredencoding(): [%s]' % pref_loc_enc) _log.debug('locale.getlocale()[1]: [%s]' % loc_enc) _log.debug('sys.getfilesystemencoding(): [%s]' % sys_fs_enc) if loc_enc is not None: loc_enc = loc_enc.upper() loc_enc_compare = loc_enc.replace('-', '') else: loc_enc_compare = loc_enc if pref_loc_enc.upper().replace('-', '') != loc_enc_compare: _log.warning( 'encoding suggested by locale (%s) does not match encoding currently set in locale (%s)' % (pref_loc_enc, loc_enc)) _log.warning('this might lead to encoding errors') for enc in [pref_loc_enc, loc_enc, py_str_enc, sys_fs_enc]: if enc is not None: try: codecs.lookup(enc) _log.debug('<codecs> module CAN handle encoding [%s]' % enc) except LookupError: _log.warning('<codecs> module can NOT handle encoding [%s]' % enc) _log.debug( 'on Linux you can determine a likely candidate for the encoding by running "locale charmap"' ) _log.debug( 'locale related environment variables (${LANG} is typically used):') for var in 'LANGUAGE LC_ALL LC_CTYPE LANG'.split(): try: _log.debug('${%s}=%s' % (var, os.environ[var])) except KeyError: _log.debug('${%s} not set' % (var)) _log.debug('database of locale conventions:') data = locale.localeconv() for key in data.keys(): if loc_enc is None: _log.debug('locale.localeconv(%s): %s', key, data[key]) else: try: _log.debug('locale.localeconv(%s): %s', key, str(data[key])) except UnicodeDecodeError: _log.debug('locale.localeconv(%s): %s', key, str(data[key], loc_enc)) _nl_langinfo_categories = {} for category in 'CODESET D_T_FMT D_FMT T_FMT T_FMT_AMPM RADIXCHAR THOUSEP YESEXPR NOEXPR CRNCYSTR ERA ERA_D_T_FMT ERA_D_FMT ALT_DIGITS'.split( ): try: _nl_langinfo_categories[category] = getattr(locale, category) except: _log.warning( 'this OS does not support nl_langinfo category locale.%s' % category) try: for category in _nl_langinfo_categories.keys(): if loc_enc is None: _log.debug( 'locale.nl_langinfo(%s): %s' % (category, locale.nl_langinfo(_nl_langinfo_categories[category]))) else: try: _log.debug( 'locale.nl_langinfo(%s): %s', category, str( locale.nl_langinfo( _nl_langinfo_categories[category]))) except UnicodeDecodeError: _log.debug( 'locale.nl_langinfo(%s): %s', category, str( locale.nl_langinfo( _nl_langinfo_categories[category]), loc_enc)) except: _log.exception('this OS does not support nl_langinfo') _log.debug('gmI18N.get_encoding(): %s', get_encoding())
def local_decimal_seperator(): return locale.localeconv()["decimal_point"]
val = int(val) if val >= 0: return True except: pass return False def format_satoshis_plain(x, decimal_point=8): """Display a satoshi amount scaled. Always uses a '.' as a decimal point and has no thousands separator""" scale_factor = pow(10, decimal_point) return "{:.8f}".format(Decimal(x) / scale_factor).rstrip('0').rstrip('.') DECIMAL_POINT = localeconv()['decimal_point'] def format_satoshis(x, num_zeros=0, decimal_point=8, precision=None, is_diff=False, whitespaces=False): if x is None: return 'unknown' if precision is None: precision = decimal_point # format string decimal_format = "." + str(precision) if precision > 0 else "" if is_diff:
def __decimal_point(self): return locale.localeconv()['decimal_point']
def text(self): text = super().text() ts = (locale.localeconv()['thousands_sep'], ' ', chr(0xA0), '.', ',') for c in ts: text = text.replace(c, '') return text
def setText(self, text): ts = locale.localeconv()['thousands_sep'] if ts == '.': text = text.replace('.', ',') super().setText(text) self._updateText()
import math import string import locale from pytd.util.sysutils import unicode_ THOUSAND_SEP = locale.localeconv()['thousands_sep'] class MemSize(long): """ define a size class to allow custom formatting format specifiers supported : em : formats the size as bits in IEC format i.e. 1024 bits (128 bytes) = 1Kib eM : formats the size as Bytes in IEC format i.e. 1024 bytes = 1KiB sm : formats the size as bits in SI format i.e. 1000 bits = 1kb sM : formats the size as bytes in SI format i.e. 1000 bytes = 1KB cm : format the size as bit in the common format i.e. 1024 bits (128 bytes) = 1Kb cM : format the size as bytes in the common format i.e. 1024 bytes = 1KB """ def __format__(self, fmt): # is it an empty format or not a special format for the size class if fmt in ("", "n"): sSep = 'n' if THOUSAND_SEP else ',' if THOUSAND_SEP and isinstance(fmt, unicode): return unicode_(long(self).__format__(sSep)) else: return long(self).__format__(sSep) elif fmt[-2:].lower() not in ["em", "sm", "cm"]: if fmt[-1].lower() in ['b', 'c', 'd', 'o', 'x', 'e', 'f', 'g', '%']: return long(self).__format__(fmt)
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import csv import xlrd import locale # import numfmt import logging from optparse import OptionParser # print "This is using python-version: " , (sys.version) locale.setlocale(locale.LC_ALL, 'en_GB') l = locale.localeconv() div1 = ',' div1000 = '.' # def xls2csv(infilepath, outfile, sheetid=1, delimiter=",", sheetdelimiter="--------", encoding="cp1251"): def xls2csv(infilepath, outfile, sheetid=1, delimiter=",", sheetdelimiter="--------", encoding="utf-8"): # Use QUOTE_NONE for no quoting of cell writer = csv.writer(outfile, dialect='excel', quoting=csv.QUOTE_NONE, delimiter=delimiter)
def __init__(self): BaseCurrency.__init__(self) self.LOCALECONV = locale.localeconv()
def load_lang(self, lang, lang_name=None): """ Create the given language if necessary, and make it active. """ # if the language exists, simply make it active language = self.with_context(active_test=False).search( [('code', '=', lang)], limit=1) if language: language.write({'active': True}) return language.id # create the language with locale information fail = True iso_lang = tools.get_iso_codes(lang) for ln in tools.get_locales(lang): try: locale.setlocale(locale.LC_ALL, str(ln)) fail = False break except locale.Error: continue if fail: lc = locale.getdefaultlocale()[0] msg = 'Unable to get information for locale %s. Information from the default locale (%s) have been used.' _logger.warning(msg, lang, lc) if not lang_name: lang_name = lang def fix_xa0(s): """Fix badly-encoded non-breaking space Unicode character from locale.localeconv(), coercing to utf-8, as some platform seem to output localeconv() in their system encoding, e.g. Windows-1252""" if s == '\xa0': return '\xc2\xa0' return s def fix_datetime_format(format): """Python's strftime supports only the format directives that are available on the platform's libc, so in order to be 100% cross-platform we map to the directives required by the C standard (1989 version), always available on platforms with a C standard implementation.""" # For some locales, nl_langinfo returns a D_FMT/T_FMT that contains # unsupported '%-' patterns, e.g. for cs_CZ format = format.replace('%-', '%') for pattern, replacement in tools.DATETIME_FORMATS_MAP.items(): format = format.replace(pattern, replacement) return str(format) conv = locale.localeconv() lang_info = { 'code': lang, 'iso_code': iso_lang, 'name': lang_name, 'active': True, 'translatable': True, 'date_format': fix_datetime_format(locale.nl_langinfo(locale.D_FMT)), 'time_format': fix_datetime_format(locale.nl_langinfo(locale.T_FMT)), 'decimal_point': fix_xa0(str(conv['decimal_point'])), 'thousands_sep': fix_xa0(str(conv['thousands_sep'])), 'grouping': str(conv.get('grouping', [])), } try: return self.create(lang_info).id finally: tools.resetlocale()
Local currency symbol : {currency_symbol!r} Symbol precedes positive value : {p_cs_precedes} Symbol precedes negative value : {n_cs_precedes} Decimal point : "{mon_decimal_point}" Digits in fractional values : {frac_digits} Digits in fractional values, international : {int_frac_digits} Grouping positions : {mon_grouping} Thousands separator : "{mon_thousands_sep}" Positive sign : "{positive_sign}" Positive sign position : {p_sign_posn} Negative sign : "{negative_sign}" Negative sign position : {n_sign_posn} """ sign_positions = { 0: 'Surrounded by parentheses', 1: 'Before value and symbol', 2: 'After value and symbol', 3: 'Before value', 4: 'After value', locale.CHAR_MAX: 'Unspecified', } info = {} info.update(locale.localeconv()) info['p_sign_posn'] = sign_positions[info['p_sign_posn']] info['n_sign_posn'] = sign_positions[info['n_sign_posn']] print(template.format(**info))
# coding=utf-8 import reprlib print(reprlib.repr(set('supercalifragilisticexpialidocious'))) print(reprlib.repr(set('supercalifrag'))) print(reprlib.repr(set('super'))) # {'e', 'p', 'r', 's', 'u'} import pprint t = [[[['black', 'cyan'], 'white', ['green', 'red']], [['magenta', 'yellow'], 'blue']]] pprint.pprint(t) # it could print a object 'hint' value import textwrap doc = """The wrap() method is just like fill() except that it returns a list of strings instead of one big string with newlines to separate the wrapped lines.""" print(textwrap.fill(doc, width=40)) import locale locale.setlocale(locale.LC_ALL, 'English_United States.1252') conv = locale.localeconv() # get a mapping of conventions x = 1234567.8 print(locale.format("%d", x, grouping=True)) print(locale.format_string("%s%.*f", (conv['currency_symbol'],conv['frac_digits'], x), grouping=True))
def get_csv_delimiter(): """Returns the csv delimiter character """ point_char = locale.localeconv()['decimal_point'] return ',' if point_char != ',' else ';'
# all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. import locale from libqtile.widget import base from libqtile.widget.generic_poll_text import GenPollUrl _DEFAULT_CURRENCY = str(locale.localeconv()['int_curr_symbol']) class BitcoinTicker(GenPollUrl): """ A bitcoin ticker widget, data provided by the coinbase.com API. Defaults to displaying currency in whatever the current locale is. Examples:: # display the average price of bitcoin in local currency widget.BitcoinTicker() # display it in Euros: widget.BitcoinTicker(currency="EUR") """ QUERY_URL = "https://api.coinbase.com/v2/prices/spot?currency=%s"