Example #1
0
def money_format(req, amount, code=None, prefix=None, suffix=None,
                 currency=None):
    if amount is None:
        return ''

    cfg = req.registry.settings
    loc = req.current_locale

    if currency is not None:
        code = currency.code
        prefix = currency.prefix
        suffix = currency.suffix

    if code is None:
        code = cfg.get('netprofile.currency.default')

    if code is None:
        formatted = format_decimal(amount, locale=loc)
    elif code in loc.currencies:
        formatted = format_currency(amount, code, locale=loc)
    else:
        stdloc = req.locales[cfg.get('pyramid.default_locale_name', 'en')]
        if code in stdloc.currencies:
            formatted = format_currency(amount, code, locale=stdloc)
        else:
            formatted = format_decimal(amount, locale=loc)

    ret = []
    if prefix:
        ret.append(prefix)
    ret.append(formatted)
    if suffix:
        ret.append(suffix)
    return '\xa0'.join(ret)
Example #2
0
 def test_patterns(self):
     self.assertEqual(numbers.format_decimal(12345, '##0',
                      locale='en_US'), '12345')
     self.assertEqual(numbers.format_decimal(6.5, '0.00', locale='sv'),
                      '6,50')
     self.assertEqual(numbers.format_decimal(10.0**20,
                                             '#.00', locale='en_US'),
                      '100000000000000000000.00')
Example #3
0
    def setupTemplates(self):
        _D = lambda x: format_decimal(x, locale="ru_RU")
        _C = lambda x: format_decimal(x, format='#,##0.00', locale="ru_RU")

        self.templates.warn = u"""Внимание! Оплата данного счета означает согласие с условиями поставки товара. Уедомление об оплате
        обязательно. В противном случае не гарантируется наличие товара на складе. Товар отпускается по факту
        прихода денег на р/с Поставщика. самовывозом при наличии доверенности и паспорта"""

        def memberTemplate(m):
            res = u"<b>{m.name}"
            if m.INN:
                res += u", ИНН {m.INN}"
            if m.KPP:
                res += u", КПП {m.KPP}"
            res += u", {m.address}"
            if m.tel:
                res += u", тел.: {m.tel}</b>"
            return res.format(m=m)

        self.templates.memberTemplate = memberTemplate

        def itemTemplate(item):
            pStyle = self.param.minStyle
            return self.Line(item.position, Paragraph(item.name, pStyle),
                             _D(item.quantity), item.units, _C(item.price),
                             _C(item.amount))

        self.templates.itemTemplate = itemTemplate

        self.templates.amountTemplate = lambda amount, due: Paragraph(
            u"Всего наименований {amount}, на сумму {due} руб.".format(
                amount=_D(amount), due=_C(due)), self.param.normalStyle)

        def spellTotal(total):
            template = u"{rubles} {kopnum:02d} {kopstr}"
            from pytils import numeral
            n = {}
            n['rubles'] = numeral.rubles(int(total)).capitalize()
            n['kopnum'] = int(total * 100) - int(total) * 100
            n['kopstr'] = numeral.choose_plural(
                n['kopnum'], (u"копейка", u"копейки", u"копеек"))
            return template.format(**n)

        self.templates.spellTotal = lambda due: Paragraph(
            u"<b>{}</b>".format(spellTotal(due)), self.param.normalStyle)

        self.templates.totalsTableTemplate = lambda total, vat, due: (
            ("", u"Итого:", _C(total)),
            ("", u"В том числе НДС:", _C(vat) if vat else u"Без НДС"),
            ("", u"Всего к оплате:", _C(due)),
        )

        from pytils.dt import ru_strftime
        self.templates.invoiceTitle = lambda invoiceNum: \
                u"Счет на оплату №{} от {}".format(str(invoiceNum),
                        ru_strftime(u"%d %B %Y", inflected=True,
                            date=self.date))
Example #4
0
    def name_bin(i, j, first_exclusive=True, last_exclusive=False):
        inclusive = format_decimal(i, format=break_formatter)
        exclusive = format_decimal(j, format=break_formatter)

        output = u'[' if first_exclusive else u'('
        output += u'%s - %s' % (inclusive, exclusive)
        output += u']' if last_exclusive else u')'

        return output
Example #5
0
    def name_bin(i, j, first_exclusive=True, last_exclusive=False):
        inclusive = format_decimal(i, format=break_formatter)
        exclusive = format_decimal(j, format=break_formatter)

        output = u'[' if first_exclusive else u'('
        output += u'%s - %s' % (inclusive, exclusive)
        output += u']' if last_exclusive else u')'

        return output
def fnum(x, decimals=None):
    if math.isinf(x):
        return '∞'

    if decimals is None:
        return format_decimal(x, locale="nl_NL")
    else:
        return format_decimal(round(x, decimals),
                              locale="nl_NL",
                              decimal_quantization=False)
Example #7
0
    def clear_all(self):
        # self.ety_garment_name.delete(0, tk.END)
        self.selected_products_counter = 0
        self.selected_products_tree.delete(
            *self.selected_products_tree.get_children())
        self.var_sheet_count.set(format_decimal(0, locale='en_US'))
        self.var_selected_quantity.set(format_decimal(0, locale='en_US'))

        self.reload_products()
        self.selected_row = list()
Example #8
0
 def _to_python(self, value, state):
   if not getattr(self, 'required', False) and not value:
       return getattr(self, 'if_missing', None)
   try:
     value = parse_decimal(value, locale = state._LOCALE_)
     if self.max and value > self.max:
       raise formencode.Invalid(self.message("amount_too_high", state, max_amount = format_decimal(self.max, locale=state._LOCALE_)), value, state)
     if self.min and value < self.min:
       raise formencode.Invalid(self.message("amount_too_low", state, min_amount = format_decimal(self.min, locale=state._LOCALE_)), value, state)
   except NumberFormatError, e:
     raise formencode.Invalid(self.message("invalid_amount", state, value = value), value, state)
Example #9
0
def format_price(price, locale='fr_fr'):
    if price == None:
        price = 0.0
        
    if type(price) <> float:
        price=float(price)
        
    if getattr(settings, 'TZ',False):
        return format_decimal(price,format='#,##0.#####;-#', locale=getattr(settings, 'TZ'))
    else:
        return format_decimal(price,format='#,##0.#####;-#', locale=locale)
Example #10
0
    def test_default_rounding(self):
        """
        Testing Round-Half-Even (Banker's rounding)

        A '5' is rounded to the closest 'even' number
        """
        self.assertEqual(numbers.format_decimal(5.5, '0', locale='sv'), '6')
        self.assertEqual(numbers.format_decimal(6.5, '0', locale='sv'), '6')
        self.assertEqual(numbers.format_decimal(6.5, '0', locale='sv'), '6')
        self.assertEqual(numbers.format_decimal(1.2325, locale='sv'), '1,232')
        self.assertEqual(numbers.format_decimal(1.2335, locale='sv'), '1,234')
Example #11
0
def test_format_decimal():
    assert numbers.format_decimal(1.2345, locale='en_US') == u'1.234'
    assert numbers.format_decimal(1.2346, locale='en_US') == u'1.235'
    assert numbers.format_decimal(-1.2346, locale='en_US') == u'-1.235'
    assert numbers.format_decimal(1.2345, locale='sv_SE') == u'1,234'
    assert numbers.format_decimal(1.2345, locale='de') == u'1,234'
    assert numbers.format_decimal(12345.5, locale='en_US') == u'12,345.5'
    assert numbers.format_decimal(0001.2345000, locale='en_US') == u'1.234'
    assert numbers.format_decimal(-0001.2346000, locale='en_US') == u'-1.235'
    assert numbers.format_decimal(0000000.5, locale='en_US') == u'0.5'
    assert numbers.format_decimal(000, locale='en_US') == u'0'
Example #12
0
def test_format_decimal():
    assert numbers.format_decimal(1.2345, locale='en_US') == u'1.234'
    assert numbers.format_decimal(1.2346, locale='en_US') == u'1.235'
    assert numbers.format_decimal(-1.2346, locale='en_US') == u'-1.235'
    assert numbers.format_decimal(1.2345, locale='sv_SE') == u'1,234'
    assert numbers.format_decimal(1.2345, locale='de') == u'1,234'
    assert numbers.format_decimal(12345.5, locale='en_US') == u'12,345.5'
    assert numbers.format_decimal(0001.2345000, locale='en_US') == u'1.234'
    assert numbers.format_decimal(-0001.2346000, locale='en_US') == u'-1.235'
    assert numbers.format_decimal(0000000.5, locale='en_US') == u'0.5'
    assert numbers.format_decimal(000, locale='en_US') == u'0'
Example #13
0
    def test_default_rounding(self):
        """
        Testing Round-Half-Even (Banker's rounding)

        A '5' is rounded to the closest 'even' number
        """
        self.assertEqual(numbers.format_decimal(5.5, '0', locale='sv'), '6')
        self.assertEqual(numbers.format_decimal(6.5, '0', locale='sv'), '6')
        self.assertEqual(numbers.format_decimal(6.5, '0', locale='sv'), '6')
        self.assertEqual(numbers.format_decimal(1.2325, locale='sv'), '1,232')
        self.assertEqual(numbers.format_decimal(1.2335, locale='sv'), '1,234')
Example #14
0
    def calculate_total_amount_and_sheet(self):
        total_sheet = 0
        total_quantity = 0
        for child in self.selected_products_tree.get_children():
            total_sheet += int(
                self.selected_products_tree.item(child)["values"][6])
            total_quantity += int(
                self.selected_products_tree.item(child)["values"][6])

        self.var_sheet_count.set(format_decimal(total_sheet, locale='en_US'))
        self.var_selected_quantity.set(
            format_decimal(total_quantity, locale='en_US'))
Example #15
0
def format_price(price, locale='fr_fr'):
    if price == None:
        price = 0.0

    if type(price) <> float:
        price = float(price)

    if getattr(settings, 'TZ', False):
        return format_decimal(price,
                              format='#,##0.#####;-#',
                              locale=getattr(settings, 'TZ'))
    else:
        return format_decimal(price, format='#,##0.#####;-#', locale=locale)
Example #16
0
 def test_decimals(self):
     """Test significant digits patterns"""
     self.assertEqual(numbers.format_decimal(Decimal('1.2345'),
                                             '#.00', locale='en_US'),
                      '1.23')
     self.assertEqual(numbers.format_decimal(Decimal('1.2345000'),
                                             '#.00', locale='en_US'),
                      '1.23')
     self.assertEqual(numbers.format_decimal(Decimal('1.2345000'),
                                             '@@', locale='en_US'),
                      '1.2')
     self.assertEqual(numbers.format_decimal(Decimal('12345678901234567890.12345'),
                                             '#.00', locale='en_US'),
                      '12345678901234567890.12')
Example #17
0
 def test_patterns(self):
     self.assertEqual(numbers.format_decimal(12345, '##0', locale='en_US'),
                      '12345')
     self.assertEqual(numbers.format_decimal(6.5, '0.00', locale='sv'),
                      '6,50')
     self.assertEqual(
         numbers.format_decimal(10.0**20, '#.00', locale='en_US'),
         '100000000000000000000.00')
     # regression test for #183, fraction digits were not correctly cutted
     # if the input was a float value and the value had more than 7
     # significant digits
     self.assertEqual(
         u'12,345,678.05',
         numbers.format_decimal(12345678.051, '#,##0.00', locale='en_US'))
Example #18
0
 def test_patterns(self):
     self.assertEqual(numbers.format_decimal(12345, '##0',
                                             locale='en_US'), '12345')
     self.assertEqual(numbers.format_decimal(6.5, '0.00', locale='sv'),
                      '6,50')
     self.assertEqual(numbers.format_decimal(10.0**20,
                                             '#.00', locale='en_US'),
                      '100000000000000000000.00')
     # regression test for #183, fraction digits were not correctly cutted
     # if the input was a float value and the value had more than 7
     # significant digits
     self.assertEqual(u'12,345,678.05',
                      numbers.format_decimal(12345678.051, '#,##0.00',
                                             locale='en_US'))
Example #19
0
def convert(in_c, out_c, count, ctx):
    rate = get_rate(in_c, out_c)
    out = {}
    result = round(number_conv(count) * float(list(rate.values())[0]), 2)
    out['in'] = "<b>{}</b> <i>{}</i>".format(
        format_decimal(number_conv(count), locale=ctx.locale),
        get_currency_name(in_c.upper(),
                          locale=ctx.locale,
                          count=number_conv(count)))
    out['out'] = "<b>{}</b> <i>{}</i>".format(
        format_decimal(result, locale=ctx.locale),
        get_currency_name(out_c.upper(),
                          locale=ctx.locale,
                          count=number_conv(count)))
    return out
Example #20
0
def i_format(loc, s, *a, **kw):
    if a:
        a = list(a)
    for c, f in [(a, enumerate), (kw, dict.items)]:
        for k, o in f(c):
            o, wrapper = (o.value, o.wrapper) if isinstance(o, Wrap) else (o, None)
            if isinstance(o, text_type):
                pass
            elif isinstance(o, Decimal):
                c[k] = format_decimal(o, locale=loc)
            elif isinstance(o, int):
                c[k] = format_number(o, locale=loc)
            elif isinstance(o, Money):
                c[k] = loc.format_money(o)
            elif isinstance(o, MoneyBasket):
                c[k] = loc.format_money_basket(o)
            elif isinstance(o, Age):
                c[k] = format_timedelta(o, locale=loc, **o.format_args)
            elif isinstance(o, timedelta):
                c[k] = format_timedelta(o, locale=loc)
            elif isinstance(o, datetime):
                c[k] = format_datetime(o, locale=loc)
            elif isinstance(o, date):
                c[k] = format_date(o, locale=loc)
            elif isinstance(o, Locale):
                c[k] = loc.languages.get(o.language) or o.language.upper()
            elif isinstance(o, Currency):
                c[k] = loc.currencies.get(o, o)
            if wrapper:
                c[k] = wrapper % (c[k],)
    return s.format(*a, **kw)
Example #21
0
def shopping_list_to_html5(shopping_list, outputfile):
    print >>outputfile, u'<html><head><link rel="stylesheet" href="shopping.css"/><meta http-equiv="content-type" content="text/html; charset=UTF-8" /></head>'
    print >>outputfile, u'<body>'
    for cat, ingredients in sorted(alg.order_by_category(shopping_list)):
        print >>outputfile, u'<h1>' + escape(cat) + u'</h1>'
        print >>outputfile, u'<table class="tbl">'
        print >>outputfile, u'  <thead>'
        print >>outputfile, u'    <tr><th></th><th colspan="2" class="amt">Mängd</th><th class="ingredient">Ingrediens</th><th class="sources">Till</th></tr>'
        print >>outputfile, u'  </thead>'
        print >>outputfile, u'  <tbody>'
        for ingredient in sorted(ingredients):
            print >>outputfile, u'  <tr>'
            print >>outputfile, u'    <td>&#x25a2;</td>'
            if ingredient.quantity:
                formatst = u"%.1f"
                print >>outputfile,u'    <td class="numeric amt-magnitude">' + format_decimal(round(ingredient.quantity.magnitude,2), locale='sv_SE') + '</td>'
                print >>outputfile,u'    <td class="amt-unit">' + escape(alg.translate_unit(unicode(ingredient.quantity.units))) + '</td>'
            else:
                print >>outputfile,u'    <td colspan="2"></td>'
            print >>outputfile,u'    <td class="ingredient">' + escape(ingredient.name) + '</td>'
            print >>outputfile,u'    <td class="sources">' + escape(", ".join([x.dish.name for x in ingredient.sources])) + '</td>'
            print >>outputfile, u'  </tr>'
        print >>outputfile, u'  </tbody>'
        print >>outputfile, u'</table>'
    print >>outputfile, u'</body></html>'
Example #22
0
def test_bar_chart():
    labels = ["One", "Two", "Three"]
    locale = "pt_br"
    chart = BarChart("ma biultiful xart", labels, data_type=ChartDataType.NUMBER, locale=locale)

    # add line data here
    with pytest.raises(AssertionError):
        chart.add_data("some lines", [1, 2, 3], ChartType.LINE)

    dataset1 = OrderedDict({"type": ChartType.BAR, "label": "some bars #1", "data": [1, 2, 3]})
    dataset2 = OrderedDict({"type": ChartType.BAR, "label": "some bars #2", "data": [2, 3, 4]})
    datasets = [dataset1, dataset2]

    chart.add_data(dataset1["label"], dataset1["data"], dataset1["type"])
    chart.add_data(dataset2["label"], dataset2["data"], dataset2["type"])

    chart_config = chart.get_config()
    assert chart_config["type"] == ChartType.BAR
    assert chart_config["data"]["labels"] == labels

    for i in range(len(chart_config["data"]["datasets"])):
        for j in range(len(chart_config["data"]["datasets"][i]["data"])):
            assert chart_config["data"]["datasets"][i]["data"][j] == datasets[i]["data"][j]

            formatted_data = chart_config["data"]["datasets"][i]["formatted_data"][j]
            assert formatted_data == format_decimal(datasets[i]["data"][j], locale=locale)
Example #23
0
def test_bar_chart():
    labels = ["One", "Two", "Three"]
    locale = "pt_br"
    chart = BarChart("ma biultiful xart", labels, data_type=ChartDataType.NUMBER, locale=locale)

    # add line data here
    with pytest.raises(AssertionError):
        chart.add_data("some lines", [1, 2, 3], ChartType.LINE)

    dataset1 = OrderedDict({"type": ChartType.BAR, "label": "some bars #1", "data": [1, 2, 3]})
    dataset2 = OrderedDict({"type": ChartType.BAR, "label": "some bars #2", "data": [2, 3, 4]})
    datasets = [dataset1, dataset2]

    chart.add_data(dataset1["label"], dataset1["data"], dataset1["type"])
    chart.add_data(dataset2["label"], dataset2["data"], dataset2["type"])

    chart_config = chart.get_config()
    assert chart_config["type"] == ChartType.BAR
    assert chart_config["data"]["labels"] == labels

    for i in range(len(chart_config["data"]["datasets"])):
        for j in range(len(chart_config["data"]["datasets"][i]["data"])):
            assert chart_config["data"]["datasets"][i]["data"][j] == datasets[i]["data"][j]

            formatted_data = chart_config["data"]["datasets"][i]["formatted_data"][j]
            assert formatted_data == format_decimal(datasets[i]["data"][j], locale=locale)
Example #24
0
    def fetch_threads_from_messages(self,
                                    channel_id,
                                    messages,
                                    max_messages,
                                    oldest=None,
                                    latest=None) -> dict:
        """returns threads from all messages from for a channel as dict"""
        threads = dict()
        thread_num = 0
        thread_messages_total = 0
        for msg in messages:
            if "thread_ts" in msg and msg["thread_ts"] == msg["ts"]:
                thread_ts = msg["thread_ts"]
                thread_num += 1
                thread_messages = self._fetch_messages_from_thread(
                    channel_id, thread_ts, max_messages, oldest, latest)
                threads[thread_ts] = thread_messages
                thread_messages_total += len(thread_messages)

        if thread_messages_total:
            logger.info(
                "Received %s messages from %d threads",
                format_decimal(thread_messages_total, locale=self._locale),
                thread_num,
            )
        else:
            logger.info("This channel has no threads")

        return threads
Example #25
0
    def links(self):
        """Get all the pagination links."""
        if self.total_pages <= 1:
            if self.show_single_page:
                return self._get_single_page_link()

            return ''

        s = [self.link_css_fmt.format(self.link_size, self.alignment)]
        s.append(self.prev_page)
        for page in self.pages:
            if self.format_number:
                try:
                    s.append(
                        format_decimal(self.single_page(page),
                                       locale=self.country_code
                                       ) if page else self.gap_marker_fmt)
                except:
                    s.append(
                        self.single_page(page) if page else self.gap_marker_fmt
                    )
            else:
                s.append(
                    self.single_page(page) if page else self.gap_marker_fmt)
        s.append(self.next_page)
        s.append(self.css_end_fmt)
        if self.css_framework == 'foundation' and self.alignment:
            s.insert(0, F_ALIGNMENT.format(self.alignment))
            s.append('</div>')

        return Markup(''.join(s))
Example #26
0
def format_decimal(d, request):
    if d is None:
        return ""
    if not isinstance(d, (float, int, decimal.Decimal)):
        return d
    l = get_locale(request)
    return numbers.format_decimal(d, locale=l)
Example #27
0
def encode_line(line):
    if line.base_unit_price.amount.value != 0:
        discount_percent = (
            line.discount_amount.amount.value /
            (line.base_unit_price.amount.value * line.quantity))
    else:
        discount_percent = 0
    return {
        "sku":
        line.sku,
        "text":
        line.text,
        "quantity":
        format_decimal(line.quantity, locale=get_current_babel_locale()),
        "unitPrice":
        format_money(line.base_unit_price.amount),
        "discountedUnitPrice":
        format_money(line.discounted_unit_price.amount),
        "discountAmount":
        format_money(line.discount_amount.amount),
        "discountPercent":
        format_percent(discount_percent, 2),
        "taxlessTotal":
        format_money(line.taxless_price.amount),
        "taxPercentage":
        format_percent(line.tax_rate, 2),
        "taxfulTotal":
        format_money(line.taxful_price.amount)
    }
Example #28
0
    def print_one(self, table, column_id, operation, label=True, **kwargs):
        """
        Print data for a single statistic.
        """
        column_name = table.column_names[column_id]

        op_name = operation
        getter = globals().get('get_%s' % op_name, None)

        with warnings.catch_warnings():
            warnings.simplefilter('ignore', agate.NullCalculationWarning)

            try:
                if getter:
                    stat = getter(table, column_id, **kwargs)
                else:
                    op = OPERATIONS[op_name]['aggregation']
                    stat = table.aggregate(op(column_id))

                    if isinstance(stat, Decimal):
                        stat = format_decimal(stat, locale=agate.config.get_option('default_locale'))
            except:
                stat = None

        # Formatting
        if op_name == 'freq':
            stat = ', '.join([(u'"%s": %s' % (six.text_type(row[column_name]), row['Count'])) for row in stat])
            stat = u'{ %s }' % stat

        if label:
            self.output_file.write(u'%3i. %s: %s\n' % (column_id + 1, column_name, stat))
        else:
            self.output_file.write(u'%s\n' % stat)
Example #29
0
def i_format(loc, s, *a, **kw):
    if a:
        a = list(a)
    for c, f in [(a, enumerate), (kw, dict.items)]:
        for k, o in f(c):
            o, wrapper = (o.value, o.wrapper) if isinstance(o, Wrap) else (o, None)
            if isinstance(o, text_type):
                pass
            elif isinstance(o, Decimal):
                c[k] = format_decimal(o, locale=loc)
            elif isinstance(o, int):
                c[k] = format_number(o, locale=loc)
            elif isinstance(o, Money):
                c[k] = loc.format_money(o)
            elif isinstance(o, MoneyBasket):
                c[k] = loc.format_money_basket(o)
            elif isinstance(o, Age):
                c[k] = format_timedelta(o, locale=loc, **o.format_args)
            elif isinstance(o, timedelta):
                c[k] = format_timedelta(o, locale=loc)
            elif isinstance(o, datetime):
                c[k] = format_datetime(o, locale=loc)
            elif isinstance(o, date):
                c[k] = format_date(o, locale=loc)
            elif isinstance(o, Locale):
                c[k] = loc.languages.get(o.language) or o.language.upper()
            elif isinstance(o, Currency):
                c[k] = loc.currencies.get(o, o)
            if wrapper:
                c[k] = wrapper % (c[k],)
    return s.format(*a, **kw)
Example #30
0
def localize_number(obj, locale, format=None, currency=None):
    """add???
    
    :param obj: add???
    :param locale: add???
    :param format: add???. Default value is ``None``
    :param currency: add???. Default value is ``None``
    :returns: add???
    """
    if format:
        flist = format.split(';')
        if len(flist) > 2:
            if obj == 0:
                return flist[2]
            else:
                format = '%s;%s' % (flist[0], flist[1])
        if currency:
            print currency
            return numbers.format_currency(obj,
                                           currency=currency,
                                           format=format,
                                           locale=locale)
        else:
            return numbers.format_decimal(obj, format=format, locale=locale)
    else:
        return numbers.format_number(obj, locale=locale)
Example #31
0
def format_decimal(number, format=None, locale=None):
    """Returns the given decimal number formatted for a specific locale.

    .. code-block:: python

       >>> format_decimal(1.2345, locale='en_US')
       u'1.234'
       >>> format_decimal(1.2346, locale='en_US')
       u'1.235'
       >>> format_decimal(-1.2346, locale='en_US')
       u'-1.235'
       >>> format_decimal(1.2345, locale='sv_SE')
       u'1,234'
       >>> format_decimal(12345, locale='de')
       u'12.345'

    The appropriate thousands grouping and the decimal separator are used for
    each locale:

    .. code-block:: python

       >>> format_decimal(12345.5, locale='en_US')
       u'12,345.5'

    :param number:
        The number to format.
    :param format:
        Notation format.
    :param locale:
        A locale code. If not set, uses the currently loaded locale.
    :returns:
        The formatted decimal number.
    """
    locale = locale or get_locale()
    return numbers.format_decimal(number, format=format, locale=locale)
def format_decimal(number, format=None, locale=None):
    """Returns the given decimal number formatted for a specific locale.

    .. code-block:: python

       >>> format_decimal(1.2345, locale='en_US')
       u'1.234'
       >>> format_decimal(1.2346, locale='en_US')
       u'1.235'
       >>> format_decimal(-1.2346, locale='en_US')
       u'-1.235'
       >>> format_decimal(1.2345, locale='sv_SE')
       u'1,234'
       >>> format_decimal(12345, locale='de')
       u'12.345'

    The appropriate thousands grouping and the decimal separator are used for
    each locale:

    .. code-block:: python

       >>> format_decimal(12345.5, locale='en_US')
       u'12,345.5'

    :param number:
        The number to format.
    :param format:
        Notation format.
    :param locale:
        A locale code. If not set, uses the currently loaded locale.
    :returns:
        The formatted decimal number.
    """
    locale = locale or get_locale()
    return numbers.format_decimal(number, format=format, locale=locale)
Example #33
0
def PrettifyNumber(
    number: int,
    locale: str = "en",
    isZeroSpecial: bool = False
) -> str:

    ##
    #
    # Returns a nicely formatted number.
    #
    # @param number        The input number.
    # @param locale        The locale to be used for formatting.
    # @param isZeroSpecial Should we replace zero with a question mark (0 -> "?")?
    #
    # @return Prettified input number.
    #
    ##

    if (0 == number) and isZeroSpecial:
        return "?"

    return format_decimal(
        number,
        locale = locale
    )
Example #34
0
 def ngettext(self, state, s, p, n, *a, **kw):
     escape = state['escape']
     n, wrapper = (n.value, n.wrapper) if isinstance(n, Wrap) else (n, None)
     n = n or 0
     msg = self.catalog._messages.get(s if s else p)
     s2 = None
     if msg:
         try:
             s2 = msg.string[self.catalog.plural_func(n)]
         except Exception as e:
             website.tell_sentry(e, state)
     if not s2:
         s2 = s if n == 1 else p
         if self is not LOCALE_EN:
             self = LOCALE_EN
             state['partial_translation'] = True
     kw['n'] = format_decimal(n, locale=self) or n
     if wrapper:
         kw['n'] = wrapper % kw['n']
     try:
         return self.format(escape(_decode(s2)), *a, **kw)
     except Exception as e:
         website.tell_sentry(e, state)
         return LOCALE_EN.format(escape(_decode(s if n == 1 else p)), *a,
                                 **kw)
Example #35
0
def test_smoke_numbers(locale):
    locale = Locale.parse(locale)
    for number in NUMBERS:
        assert numbers.format_decimal(number, locale=locale)
        assert numbers.format_currency(number, "EUR", locale=locale)
        assert numbers.format_scientific(number, locale=locale)
        assert numbers.format_percent(number / 100, locale=locale)
Example #36
0
    def add_data(self, name, data, chart_type):
        """
        Add data to this chart
        :param name: the name of the dataset
        :type name: str
        :param data: the list of data
        :type data: list[int|float|Decimal]
        :param chart_type: the chart type - tells how data should be rendered.
            This data type must be available in the `supported_chart_type` attribute of this instance
        :type chart_type: ChartType
        """
        assert chart_type in self.supported_chart_types
        formatted_data = []

        # format value for each data point
        if self.data_type == ChartDataType.CURRENCY:
            for value in data:
                formatted_data.append(format_money(Money(value, currency=self.currency).as_rounded()))

        elif self.data_type == ChartDataType.PERCENT:
            for value in data:
                formatted_data.append(format_percent(value, locale=self.locale))

        # self.data_type == ChartDataType.NUMBER
        else:
            for value in data:
                formatted_data.append(format_decimal(value, locale=self.locale))

        self.datasets.append({"type": chart_type, "label": name, "data": data, "formatted_data": formatted_data})
Example #37
0
    def add_data(self, name, data, chart_type):
        """
        Add data to this chart
        :param name: the name of the dataset
        :type name: str
        :param data: the list of data
        :type data: list[int|float|Decimal]
        :param chart_type: the chart type - tells how data should be rendered.
            This data type must be available in the `supported_chart_type` attribute of this instance
        :type chart_type: ChartType
        """
        assert chart_type in self.supported_chart_types
        formatted_data = []

        # format value for each data point
        if self.data_type == ChartDataType.CURRENCY:
            for value in data:
                formatted_data.append(format_money(Money(value, currency=self.currency).as_rounded()))

        elif self.data_type == ChartDataType.PERCENT:
            for value in data:
                formatted_data.append(format_percent(value, locale=self.locale))

        # self.data_type == ChartDataType.NUMBER
        else:
            for value in data:
                formatted_data.append(format_decimal(value, locale=self.locale))

        self.datasets.append({"type": chart_type, "label": name, "data": data, "formatted_data": formatted_data})
Example #38
0
    def format_number_ms(self,
                         number,
                         strformat="#,###.##",
                         strlocale="en_US",
                         currency="USD"):
        """
        Apply the Locale Data Markup Language Specification: http://unicode.org/reports/tr35/tr35-numbers.html#Number_Format_Patterns
        Just Babel library do that on python: http://babel.pocoo.org/docs/numbers/ / https://github.com/mitsuhiko/babel
        """
        #REQUIRE sudo pip install babel
        #if not unicode(number).isnumeric():
        #    return number #False

        if number == "":  # empty strings are BAD
            return 0
        if strformat == "":
            return number
        #maybe babe is not installed
        try:
            if (strformat.find("$") > -1 or strformat.find(u"\u00A4") > -1
                    or currency == ""):
                # strformat = unicode(strformat.replace("$", u"\u00A4"))
                res = numbers.format_currency(float(number),
                                              currency,
                                              format=strformat,
                                              locale=strlocale)
            else:
                res = numbers.format_decimal(float(number),
                                             format=strformat,
                                             locale=strlocale)
        except:
            err = str(sys.exc_info())
            res = str(number) + " error " + err

        return res
Example #39
0
 def asString(self, objValue, objType):
     '''
     @see: Converter.asString
     '''
     assert isinstance(objType, Type), 'Invalid object type %s' % objType
     if isinstance(objType, TypeModel): # If type model is provided we consider the model property type
         assert isinstance(objType, TypeModel)
         container = objType.container
         assert isinstance(container, Model)
         objType = container.properties[container.propertyId]
     if objType.isOf(str):
         return objValue
     if objType.isOf(bool):
         return str(objValue)
     if objType.isOf(Percentage):
         return bn.format_percent(objValue, self.formats.get(Percentage, None), self.locale)
     if objType.isOf(Number):
         return bn.format_decimal(objValue, self.formats.get(Number, None), self.locale)
     if objType.isOf(Date):
         return bd.format_date(objValue, self.formats.get(Date, None), self.locale)
     if objType.isOf(Time):
         return bd.format_time(objValue, self.formats.get(Time, None), self.locale)
     if objType.isOf(DateTime):
         return bd.format_datetime(objValue, self.formats.get(DateTime, None), None, self.locale)
     raise TypeError('Invalid object type %s for Babel converter' % objType)
Example #40
0
    def format_number_ms(self, number, strformat="#,###.##", strlocale="en_US", currency="USD"):
        """
        Apply the Locale Data Markup Language Specification: http://unicode.org/reports/tr35/tr35-numbers.html#Number_Format_Patterns
        Just Babel library do that on python: http://babel.pocoo.org/docs/numbers/ / https://github.com/mitsuhiko/babel
        """
        #REQUIRE sudo pip install babel
        #if not unicode(number).isnumeric():
        #    return number #False

        if number == "": # empty strings are BAD
            return 0
        if strformat == "":
            return number
        #maybe babe is not installed
        try:
            if (strformat.find("$") > -1 or strformat.find(u"\u00A4") > -1 or currency == ""):
                # strformat = unicode(strformat.replace("$", u"\u00A4"))
                res = numbers.format_currency(float(number), currency, format=strformat, locale=strlocale)
            else:
                res = numbers.format_decimal(float(number), format=strformat, locale=strlocale)
        except:
            err = str(sys.exc_info())
            res = str(number) + " error " + err

        return res
Example #41
0
 def format(self, s, *a, **kw):
     if a:
         a = list(a)
     for c, f in [(a, enumerate), (kw, dict.items)]:
         for k, o in f(c):
             o, wrapper = (o.value, o.wrapper) if isinstance(o, Wrap) else (o, None)
             if isinstance(o, str):
                 pass
             elif isinstance(o, (Decimal, int)):
                 c[k] = format_decimal(o, locale=self)
             elif isinstance(o, Money):
                 c[k] = self.format_money(o)
             elif isinstance(o, MoneyBasket):
                 c[k] = self.format_money_basket(o)
             elif isinstance(o, timedelta):
                 c[k] = self.format_timedelta(o)
             elif isinstance(o, date):
                 if isinstance(o, datetime):
                     c[k] = format_datetime(o, locale=self)
                 else:
                     c[k] = format_date(o, locale=self)
             elif isinstance(o, Locale):
                 c[k] = self.languages.get(o.language) or o.language.upper()
             elif isinstance(o, Country):
                 c[k] = self.countries.get(o, o)
             elif isinstance(o, Currency):
                 c[k] = self.currencies.get(o, o)
             elif isinstance(o, list):
                 escape = getattr(s.__class__, 'escape', no_escape)
                 pattern = getattr(o, 'pattern', 'standard')
                 c[k] = self.format_list(o, pattern, escape)
             if wrapper:
                 c[k] = wrapper % (c[k],)
     return s.format(*a, **kw)
Example #42
0
def format_decimal(number, format=None):
    """Returns the given decimal number formatted for a specific locale.

    >>> format_decimal(1.2345, locale='en_US')
    u'1.234'
    >>> format_decimal(1.2346, locale='en_US')
    u'1.235'
    >>> format_decimal(-1.2346, locale='en_US')
    u'-1.235'
    >>> format_decimal(1.2345, locale='sv_SE')
    u'1,234'
    >>> format_decimal(12345, locale='de')
    u'12.345'

    The appropriate thousands grouping and the decimal separator are used for
    each locale:

    >>> format_decimal(12345.5, locale='en_US')
    u'12,345.5'

    :param number:
        The number to format.
    :param format:
    :return:
        The formatted decimal number.
    """
    return numbers.format_decimal(number, format=format, locale=local.locale)
Example #43
0
    def calculate_stats(self, table, column_id, **kwargs):
        """
        Calculate stats for all valid operations.
        """
        stats = {}

        for op_name, op_data in OPERATIONS.items():
            getter = globals().get('get_%s' % op_name, None)

            with warnings.catch_warnings():
                warnings.simplefilter('ignore', agate.NullCalculationWarning)

                try:
                    if getter:
                        stats[op_name] = getter(table, column_id, **kwargs)
                    else:
                        op = op_data['aggregation']
                        v = table.aggregate(op(column_id))

                        if isinstance(v, Decimal):
                            v = format_decimal(v, locale=agate.config.get_option('default_locale'))

                        stats[op_name] = v
                except:
                    stats[op_name] = None

        return stats
Example #44
0
 def format(self, s, *a, **kw):
     if a:
         a = list(a)
     for c, f in [(a, enumerate), (kw, dict.items)]:
         for k, o in f(c):
             o, wrapper = (o.value,
                           o.wrapper) if isinstance(o, Wrap) else (o, None)
             if isinstance(o, text_type):
                 pass
             elif isinstance(o, (Decimal, int)):
                 c[k] = format_decimal(o, locale=self)
             elif isinstance(o, Money):
                 c[k] = self.format_money(o)
             elif isinstance(o, MoneyBasket):
                 c[k] = self.format_money_basket(o)
             elif isinstance(o, timedelta):
                 c[k] = self.format_timedelta(o)
             elif isinstance(o, date):
                 if isinstance(o, datetime):
                     c[k] = format_datetime(o, locale=self)
                 else:
                     c[k] = format_date(o, locale=self)
             elif isinstance(o, Locale):
                 c[k] = self.languages.get(o.language) or o.language.upper()
             elif isinstance(o, Country):
                 c[k] = self.countries.get(o, o)
             elif isinstance(o, Currency):
                 c[k] = self.currencies.get(o, o)
             if wrapper:
                 c[k] = wrapper % (c[k], )
     return s.format(*a, **kw)
Example #45
0
def money_format_long(req, amount, code=None, currency=None):
    if amount is None:
        return ''

    cfg = req.registry.settings
    loc = req.current_locale

    if currency is not None:
        code = currency.code

    if code is None:
        code = cfg.get('netprofile.currency.default')

    if code is not None:
        if code in loc.currencies:
            return format_currency(amount, code, locale=loc,
                                   format='0.######## ¤¤¤',
                                   currency_digits=False)
        else:
            stdloc = req.locales[cfg.get('pyramid.default_locale_name', 'en')]
            if code in stdloc.currencies:
                return format_currency(amount, code, locale=stdloc,
                                       format='0.######## ¤¤¤',
                                       currency_digits=False)

    return format_decimal(amount, locale=loc, format='0.########')
Example #46
0
    def data(self, index: QtCore.QModelIndex, role: int = ...) -> typing.Any:

        index_row = index.row()
        index_column = index.column()

        if role in (QtCore.Qt.DisplayRole, QtCore.Qt.EditRole):
            unit_horizontal = self._unit_list[index_column]
            unit_vertical = self._unit_list[index_row]
            value = None

            # The same unit
            if index_row == index_column:
                value = 1

            # Compensate for a bug initializing the database with wrong defaults
            elif unit_vertical.factor is not None and unit_horizontal.factor is not None:
                value = unit_vertical.factor / unit_horizontal.factor
            if value is not None:
                if unit_horizontal.cldr and role == QtCore.Qt.DisplayRole:
                    return QtCore.QVariant(format_unit(value, unit_horizontal.name, length="short"))
                return QtCore.QVariant(format_decimal(value))

        if role == QtCore.Qt.FontRole:
            if index_row == index_column:
                return self.bold_font

        return None
Example #47
0
    def format_decimal(self, number, format=None):
        """Returns the given decimal number formatted for the current locale.
        Example::

            >>> format_decimal(1.2345, locale='en_US')
            u'1.234'
            >>> format_decimal(1.2346, locale='en_US')
            u'1.235'
            >>> format_decimal(-1.2346, locale='en_US')
            u'-1.235'
            >>> format_decimal(1.2345, locale='sv_SE')
            u'1,234'
            >>> format_decimal(12345, locale='de')
            u'12.345'

        The appropriate thousands grouping and the decimal separator are used
        for each locale::

            >>> format_decimal(12345.5, locale='en_US')
            u'12,345.5'

        :param number:
            The number to format.
        :param format:
            Notation format.
        :returns:
            The formatted decimal number.
        """
        return numbers.format_decimal(number, format=format,
                                      locale=self.locale)
Example #48
0
    def format_decimal(self, number, format=None):
        """Returns the given decimal number formatted for the current locale.
        Example::

            >>> format_decimal(1.2345, locale='en_US')
            u'1.234'
            >>> format_decimal(1.2346, locale='en_US')
            u'1.235'
            >>> format_decimal(-1.2346, locale='en_US')
            u'-1.235'
            >>> format_decimal(1.2345, locale='sv_SE')
            u'1,234'
            >>> format_decimal(12345, locale='de')
            u'12.345'

        The appropriate thousands grouping and the decimal separator are used
        for each locale::

            >>> format_decimal(12345.5, locale='en_US')
            u'12,345.5'

        :param number:
            The number to format.
        :param format:
            Notation format.
        :returns:
            The formatted decimal number.
        """
        return numbers.format_decimal(number, format=format,
                                      locale=self.locale)
Example #49
0
    def decimal(self, number, format=None):
        """Return a decimal number formatted for the locale.

        >>> fmt = Format('en_US')
        >>> fmt.decimal(1.2345)
        u'1.234'
        """
        return format_decimal(number, format, locale=self.locale)
Example #50
0
def number(context, n):
    """Return the localized representation of an integer or decimal.

    For None, print nothing.

    """
    if n is None:
        return ""
    return format_decimal(n, locale=_babel_locale(_contextual_locale(context)))
Example #51
0
def format_number(value, digits=None):
    locale = get_current_babel_locale()
    if digits is None:
        return format_decimal(value, locale=locale)
    (min_digits, max_digits) = (
        digits if isinstance(digits, tuple) else (digits, digits))
    format = locale.decimal_formats.get(None)
    pattern = parse_pattern(format)  # type: babel.numbers.NumberPattern
    return pattern.apply(value, locale, force_frac=(min_digits, max_digits))
Example #52
0
File: locale.py Project: 20c/vodka1
 def fmt_number(self, n, prec):
   prec = int(prec)
   fmt = "#0"
   if prec:
     z = "0"
     z = z.rjust(prec, "0")
     fmt = fmt + "." + z
   #print "FMT prec " + str(prec) + " fmt " + fmt
   return format_decimal(n, format=fmt, locale=self._locale)
Example #53
0
    def print_stats(self, table, column_ids, stats):
        """
        Print data for all statistics.
        """
        label_column_width = max([len(op_data['label']) for op_data in OPERATIONS.values()])

        for column_id in column_ids:
            column_name = table.column_names[column_id]
            column = table.columns[column_id]
            column_stats = stats[column_id]

            self.output_file.write(('%3i. "%s"\n\n' % (column_id + 1, column_name)))

            for op_name, op_data in OPERATIONS.items():
                if column_stats[op_name] is None:
                    continue

                label = u'{label:{label_column_width}}'.format(**{
                    'label_column_width': label_column_width,
                    'label': op_data['label']
                })

                if op_name == 'freq':
                    for i, row in enumerate(column_stats['freq']):
                        if i == 0:
                            self.output_file.write('\t{} '.format(label))
                        else:
                            self.output_file.write(u'\t{label:{label_column_width}} '.format(**{
                                'label_column_width': label_column_width,
                                'label': ''
                            }))

                        if isinstance(column.data_type, agate.Number):
                            v = row[column_name]

                            if isinstance(v, Decimal):
                                v = format_decimal(v, locale=agate.config.get_option('default_locale'))
                        else:
                            v = six.text_type(row[column_name])

                        self.output_file.write(u'{} ({}x)\n'.format(v, row['Count']))

                    continue

                v = column_stats[op_name]

                if op_name == 'nulls' and v:
                    v = '%s (excluded from calculations)' % v
                elif op_name == 'len':
                    v = '%s characters' % v

                self.output_file.write(u'\t{} {}\n'.format(label, v))

            self.output_file.write('\n')

        self.output_file.write('Row count: %s\n' % len(table.rows))
Example #54
0
 def decimal(self, number, format=None):
     """Return a decimal number formatted for the locale.
     
     >>> fmt = Format('en_US')
     >>> fmt.decimal(1.2345) == u('1.234')
     True
     
     :see: `babel.numbers.format_decimal`
     """
     return format_decimal(number, format, locale=self.locale)
Example #55
0
def format_decimal(number, format=None):
    """Return the given decimal number formatted for the locale in request

    :param number: the number to format
    :param format: the format to use
    :return: the formatted number
    :rtype: unicode
    """
    locale = get_locale()
    return numbers.format_decimal(number, format=format, locale=locale)
Example #56
0
def test_smoke_numbers(locale):
    locale = Locale.parse(locale)
    for number in (
        decimal.Decimal("-33.76"),  # Negative Decimal
        decimal.Decimal("13.37"),  # Positive Decimal
        1.2 - 1.0,  # Inaccurate float
        10,  # Plain old integer
        0,  # Zero
    ):
        assert numbers.format_decimal(number, locale=locale)