Python locale.format_string() Examples
The following are 30
code examples of locale.format_string().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
locale
, or try the search function
.
Example #1
Source File: Formatter.py From urh with GNU General Public License v3.0 | 8 votes |
def big_value_with_suffix(value: float, decimals=3, strip_zeros=True) -> str: fmt_str = "%.{0:d}f".format(decimals) suffix = "" if abs(value) >= 1e9: suffix = "G" result = locale.format_string(fmt_str, value / 1e9) elif abs(value) >= 1e6: suffix = "M" result = locale.format_string(fmt_str, value / 1e6) elif abs(value) >= 1e3: suffix = "K" result = locale.format_string(fmt_str, value / 1e3) else: result = locale.format_string(fmt_str, value) if strip_zeros: result = result.rstrip("0").rstrip(Formatter.local_decimal_seperator()) return result + suffix
Example #2
Source File: test_format_float.py From barril with MIT License | 7 votes |
def testFormatFloat(): """ Convert unit of scalar where value is "0.0". """ assert FormatFloat("%g", 0.0) == "0" assert FormatFloat("%g", -0.0) == "0" scalar = Scalar("length", 0.0, "m") assert FormatFloat("%g", scalar.GetValue()) == "0" assert locale.format_string("%g", scalar.GetValue("ft")) == "-0" assert FormatFloat("%g", scalar.GetValue("ft")) == "0" # Large float numbers on integer format. large_float_number = 1e010 * 1.0 assert FormatFloat("%d", large_float_number) == "10000000000" # Infinity assert FormatFloat("%.3g", PLUS_INFINITY) == "+INF" assert FormatFloat("%.3g", MINUS_INFINITY) == "-INF" assert FormatFloat("%.3g", NAN) == "-1.#IND" # Digit grouping assert FormatFloat("%.2f", 1234567, False) == "1234567.00" assert FormatFloat("%.2f", 1234567, True) == "1234567.00"
Example #3
Source File: test_types.py From android_universal with MIT License | 6 votes |
def test_int__format__locale(self): # test locale support for __format__ code 'n' for integers x = 123456789012345678901234567890 for i in range(0, 30): self.assertEqual(locale.format_string('%d', x, grouping=True), format(x, 'n')) # move to the next integer to test x = x // 10 rfmt = ">20n" lfmt = "<20n" cfmt = "^20n" for x in (1234, 12345, 123456, 1234567, 12345678, 123456789, 1234567890, 12345678900): self.assertEqual(len(format(0, rfmt)), len(format(x, rfmt))) self.assertEqual(len(format(0, lfmt)), len(format(x, lfmt))) self.assertEqual(len(format(0, cfmt)), len(format(x, cfmt)))
Example #4
Source File: functions.py From docassemble with MIT License | 6 votes |
def nice_number_default(the_number, **kwargs): """Returns the number as a word in the current language.""" capitalize = kwargs.get('capitalize', False) language = kwargs.get('language', None) ensure_definition(the_number, capitalize, language) if language is None: language = this_thread.language if language in nice_numbers: language_to_use = language elif '*' in nice_numbers: language_to_use = '*' else: language_to_use = 'en' if int(float(the_number)) == float(the_number): the_number = int(float(the_number)) if str(the_number) in nice_numbers[language_to_use]: the_word = nice_numbers[language_to_use][str(the_number)] if capitalize: return capitalize_function(the_word) else: return the_word elif type(the_number) is int: return str(locale.format_string("%d", the_number, grouping=True)) else: return str(locale.format_string("%.2f", float(the_number), grouping=True)).rstrip('0')
Example #5
Source File: ticker.py From twitter-stock-recommendation with MIT License | 5 votes |
def format_data_short(self, value): """ Return a short formatted string representation of a number. """ if self._useLocale: return locale.format_string('%-12g', (value,)) else: return '%-12g' % value
Example #6
Source File: test_locale.py From CTFCrackTools-V2 with GNU General Public License v3.0 | 5 votes |
def _test_format_string(self, format, value, out, **format_opts): self._test_formatfunc(format, value, out, func=locale.format_string, **format_opts)
Example #7
Source File: test_locale.py From CTFCrackTools-V2 with GNU General Public License v3.0 | 5 votes |
def test_percent_escape(self): self.assertEqual(locale.format_string('%f%%', 1.0), '%f%%' % 1.0) self.assertEqual(locale.format_string('%d %f%%d', (1, 1.0)), '%d %f%%d' % (1, 1.0)) self.assertEqual(locale.format_string('%(foo)s %%d', {'foo': 'bar'}), ('%(foo)s %%d' % {'foo': 'bar'}))
Example #8
Source File: __init__.py From Greynir with GNU General Public License v3.0 | 5 votes |
def format_icelandic_float(fp_num): """ Convert number to Icelandic decimal format. """ with changedlocale(category="LC_NUMERIC"): res = locale.format_string("%.2f", fp_num, grouping=True).replace(" ", ".") return strip_trailing_zeros(res)
Example #9
Source File: ticker.py From twitter-stock-recommendation with MIT License | 5 votes |
def pprint_val(self, x): xp = (x - self.offset) / (10. ** self.orderOfMagnitude) if np.abs(xp) < 1e-8: xp = 0 if self._useLocale: return locale.format_string(self.format, (xp,)) else: return self.format % xp
Example #10
Source File: ticker.py From twitter-stock-recommendation with MIT License | 5 votes |
def format_data(self, value): """ Return a formatted string representation of a number. """ if self._useLocale: s = locale.format_string('%1.10e', (value,)) else: s = '%1.10e' % value s = self._formatSciNotation(s) return self.fix_minus(s)
Example #11
Source File: SendRecvDialog.py From urh with GNU General Public License v3.0 | 5 votes |
def update_view(self): try: self.ui.sliderYscale.setValue(int(self.graphics_view.transform().m22())) except AttributeError: return txt = self.ui.txtEditErrors.toPlainText() new_messages = self.device.read_messages() self.__parse_error_messages(new_messages) if len(new_messages) > 1: self.ui.txtEditErrors.setPlainText(txt + new_messages) self.ui.lSamplesCaptured.setText(Formatter.big_value_with_suffix(self.device.current_index, decimals=1)) self.ui.lSignalSize.setText(locale.format_string("%.2f", (8 * self.device.current_index) / (1024 ** 2))) self.ui.lTime.setText(locale.format_string("%.2f", self.device.current_index / self.device.sample_rate)) if self.is_rx and self.device.data is not None and len(self.device.data) > 0: self.ui.labelReceiveBufferFull.setText("{0}%".format(int(100 * self.device.current_index / len(self.device.data)))) if self.device.current_index == 0: return False return True
Example #12
Source File: test_locale.py From CTFCrackTools with GNU General Public License v3.0 | 5 votes |
def test_mapping(self): self.assertEqual(locale.format_string('%(foo)s bing.', {'foo': 'bar'}), ('%(foo)s bing.' % {'foo': 'bar'})) self.assertEqual(locale.format_string('%(foo)s', {'foo': 'bar'}), ('%(foo)s' % {'foo': 'bar'}))
Example #13
Source File: test_locale.py From CTFCrackTools with GNU General Public License v3.0 | 5 votes |
def test_percent_escape(self): self.assertEqual(locale.format_string('%f%%', 1.0), '%f%%' % 1.0) self.assertEqual(locale.format_string('%d %f%%d', (1, 1.0)), '%d %f%%d' % (1, 1.0)) self.assertEqual(locale.format_string('%(foo)s %%d', {'foo': 'bar'}), ('%(foo)s %%d' % {'foo': 'bar'}))
Example #14
Source File: test_locale.py From CTFCrackTools with GNU General Public License v3.0 | 5 votes |
def _test_format_string(self, format, value, out, **format_opts): self._test_formatfunc(format, value, out, func=locale.format_string, **format_opts)
Example #15
Source File: test_types.py From android_universal with MIT License | 5 votes |
def test_float__format__locale(self): # test locale support for __format__ code 'n' for i in range(-10, 10): x = 1234567890.0 * (10.0 ** i) self.assertEqual(locale.format_string('%g', x, grouping=True), format(x, 'n')) self.assertEqual(locale.format_string('%.10g', x, grouping=True), format(x, '.10n'))
Example #16
Source File: functions.py From docassemble with MIT License | 5 votes |
def currency_default(value, **kwargs): """Returns the value as a currency, according to the conventions of the current locale. Use the optional keyword argument decimals=False if you do not want to see decimal places in the number, and the optional currency_symbol for a different symbol than the default. """ decimals = kwargs.get('decimals', True) symbol = kwargs.get('symbol', None) ensure_definition(value, decimals, symbol) obj_type = type(value).__name__ if obj_type in ['FinancialList', 'PeriodicFinancialList']: value = value.total() elif obj_type in ['Value', 'PeriodicValue']: if value.exists: value = value.amount() else: value = 0 elif obj_type == 'DACatchAll': value = float(value) try: float(value) except: return '' the_symbol = None if symbol is not None: the_symbol = symbol elif this_thread.misc.get('currency symbol', None) not in (None, ''): the_symbol = this_thread.misc['currency symbol'] elif language_functions['currency_symbol']['*'] is not currency_symbol_default: the_symbol = currency_symbol() if the_symbol is None: if decimals: return str(locale.currency(float(value), symbol=True, grouping=True)) else: return currency_symbol() + locale.format_string("%d", int(float(value)), grouping=True) if decimals: return the_symbol + locale.format_string('%.' + str(server.daconfig.get('currency decimal places', 2)) + 'f', float(value), grouping=True) else: return the_symbol + locale.format_string("%d", int(float(value)), grouping=True)
Example #17
Source File: ticker.py From coffeegrindsize with MIT License | 5 votes |
def format_data(self, value): """ Return a formatted string representation of a number. """ if self._useLocale: s = locale.format_string('%1.10e', (value,)) else: s = '%1.10e' % value s = self._formatSciNotation(s) return self.fix_minus(s)
Example #18
Source File: SignalDetailsDialog.py From urh with GNU General Public License v3.0 | 5 votes |
def __init__(self, signal, parent=None): super().__init__(parent) self.signal = signal self.ui = Ui_SignalDetails() self.ui.setupUi(self) self.setAttribute(Qt.WA_DeleteOnClose) self.setWindowFlags(Qt.Window) file = self.signal.filename self.ui.lblName.setText(self.signal.name) if os.path.isfile(file): self.ui.lblFile.setText(file) self.ui.lblFileSize.setText(locale.format_string("%.2fMB", os.path.getsize(file) / (1024 ** 2))) self.ui.lFileCreated.setText(time.ctime(os.path.getctime(file))) else: self.ui.lblFile.setText(self.tr("signal file not found")) self.ui.lblFileSize.setText("-") self.ui.lFileCreated.setText("-") self.ui.lblSamplesTotal.setText("{0:n}".format(self.signal.num_samples).replace(",", " ")) self.ui.dsb_sample_rate.setValue(self.signal.sample_rate) self.set_duration() self.ui.dsb_sample_rate.valueChanged.connect(self.on_dsb_sample_rate_value_changed) self.restoreGeometry(settings.read("{}/geometry".format(self.__class__.__name__), type=bytes))
Example #19
Source File: ticker.py From coffeegrindsize with MIT License | 5 votes |
def format_data_short(self, value): """ Return a short formatted string representation of a number. """ if self._useLocale: return locale.format_string('%-12g', (value,)) else: return '%-12g' % value
Example #20
Source File: GeneratorTabController.py From urh with GNU General Public License v3.0 | 5 votes |
def refresh_estimated_time(self): c = self.table_model.protocol if c.num_messages == 0: self.ui.lEstimatedTime.setText("Estimated Time: ") return avg_msg_len = numpy.mean([len(msg.encoded_bits) for msg in c.messages]) avg_samples_per_symbol = numpy.mean([m.samples_per_symbol for m in self.modulators]) avg_sample_rate = numpy.mean([m.sample_rate for m in self.modulators]) pause_samples = sum(c.pauses) nsamples = c.num_messages * avg_msg_len * avg_samples_per_symbol + pause_samples self.ui.lEstimatedTime.setText( locale.format_string("Estimated Time: %.04f seconds", nsamples / avg_sample_rate))
Example #21
Source File: CompareFrameController.py From urh with GNU General Public License v3.0 | 5 votes |
def __set_decoding_error_label(self, message: Message): if message: errors = message.decoding_errors percent = 100 * (errors / len(message)) state = message.decoding_state if message.decoding_state != message.decoder.ErrorState.SUCCESS else "" color = "green" if errors == 0 and state == "" else "red" self.ui.lDecodingErrorsValue.setStyleSheet("color: " + color) self.ui.lDecodingErrorsValue.setText(locale.format_string("%d (%.02f%%) %s", (errors, percent, state))) else: self.ui.lDecodingErrorsValue.setText("No message selected")
Example #22
Source File: Modulator.py From urh with GNU General Public License v3.0 | 5 votes |
def get_value_with_suffix(value, unit=""): decimal_point = locale.localeconv()["decimal_point"] if abs(value) >= 10 ** 9: target_val, suffix = value / 10 ** 9, "G" elif abs(value) >= 10 ** 6: target_val, suffix = value / 10 ** 6, "M" elif abs(value) >= 10 ** 3: target_val, suffix = value / 10 ** 3, "k" else: target_val, suffix = value, "" return locale.format_string("%.3f", target_val).rstrip("0").rstrip(decimal_point) + suffix + unit
Example #23
Source File: test_locale.py From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 | 5 votes |
def test_mapping(self): self.assertEqual(locale.format_string('%(foo)s bing.', {'foo': 'bar'}), ('%(foo)s bing.' % {'foo': 'bar'})) self.assertEqual(locale.format_string('%(foo)s', {'foo': 'bar'}), ('%(foo)s' % {'foo': 'bar'}))
Example #24
Source File: test_locale.py From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 | 5 votes |
def test_percent_escape(self): self.assertEqual(locale.format_string('%f%%', 1.0), '%f%%' % 1.0) self.assertEqual(locale.format_string('%d %f%%d', (1, 1.0)), '%d %f%%d' % (1, 1.0)) self.assertEqual(locale.format_string('%(foo)s %%d', {'foo': 'bar'}), ('%(foo)s %%d' % {'foo': 'bar'}))
Example #25
Source File: test_locale.py From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 | 5 votes |
def _test_format_string(self, format, value, out, **format_opts): self._test_formatfunc(format, value, out, func=locale.format_string, **format_opts)
Example #26
Source File: bot.py From telegram-moderator with MIT License | 5 votes |
def decimal_format(v, decimals=2): if not v: v = 0 f = locale.format_string('%.{}f'.format(decimals), v, grouping=True) return '{}'.format(f)
Example #27
Source File: test_locale.py From gcblue with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_mapping(self): self.assertEqual(locale.format_string('%(foo)s bing.', {'foo': 'bar'}), ('%(foo)s bing.' % {'foo': 'bar'})) self.assertEqual(locale.format_string('%(foo)s', {'foo': 'bar'}), ('%(foo)s' % {'foo': 'bar'}))
Example #28
Source File: test_locale.py From gcblue with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_percent_escape(self): self.assertEqual(locale.format_string('%f%%', 1.0), '%f%%' % 1.0) self.assertEqual(locale.format_string('%d %f%%d', (1, 1.0)), '%d %f%%d' % (1, 1.0)) self.assertEqual(locale.format_string('%(foo)s %%d', {'foo': 'bar'}), ('%(foo)s %%d' % {'foo': 'bar'}))
Example #29
Source File: test_locale.py From gcblue with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _test_format_string(self, format, value, out, **format_opts): self._test_formatfunc(format, value, out, func=locale.format_string, **format_opts)
Example #30
Source File: ticker.py From ImageFusion with MIT License | 5 votes |
def pprint_val(self, x): xp = (x - self.offset) / (10. ** self.orderOfMagnitude) if np.absolute(xp) < 1e-8: xp = 0 if self._useLocale: return locale.format_string(self.format, (xp,)) else: return self.format % xp