• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python numbers.format_decimal函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中babel.numbers.format_decimal函数的典型用法代码示例。如果您正苦于以下问题:Python format_decimal函数的具体用法?Python format_decimal怎么用?Python format_decimal使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了format_decimal函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: money_format

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)
开发者ID:unikmhz,项目名称:npui,代码行数:34,代码来源:locale.py


示例2: test_patterns

 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')
开发者ID:vsajip,项目名称:babel3,代码行数:8,代码来源:numbers.py


示例3: name_bin

    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
开发者ID:elaOnMars,项目名称:agate,代码行数:9,代码来源:bins.py


示例4: test_default_rounding

    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')
开发者ID:vsajip,项目名称:babel3,代码行数:11,代码来源:numbers.py


示例5: test_format_decimal

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'
开发者ID:JonathanRRogers,项目名称:babel,代码行数:11,代码来源:test_numbers.py


示例6: _to_python

 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)
开发者ID:larryslist,项目名称:larryslist_pub,代码行数:11,代码来源:validators.py


示例7: format_price

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)
开发者ID:tonyPayetDev,项目名称:app_blacklist,代码行数:11,代码来源:tools.py


示例8: test_patterns

 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'))
开发者ID:gmist,项目名称:babel,代码行数:14,代码来源:test_numbers.py


示例9: test_decimals

 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')
开发者ID:vsajip,项目名称:babel3,代码行数:14,代码来源:numbers.py


示例10: add_data

    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})
开发者ID:gurch101,项目名称:shuup,代码行数:29,代码来源:charts.py


示例11: test_bar_chart

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)
开发者ID:gurch101,项目名称:shuup,代码行数:26,代码来源:test_chart.py


示例12: format_decimal

    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)
开发者ID:404minds,项目名称:quiz-forest,代码行数:30,代码来源:i18n.py


示例13: asString

 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)
开发者ID:ahilles107,项目名称:Superdesk,代码行数:25,代码来源:text_conversion.py


示例14: format_decimal

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)
开发者ID:Hubble1,项目名称:eventgrinder,代码行数:35,代码来源:i18n.py


示例15: print_one

    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)
开发者ID:skorasaurus,项目名称:csvkit,代码行数:33,代码来源:csvstat.py


示例16: i_format

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)
开发者ID:devmiyax,项目名称:liberapay.com,代码行数:31,代码来源:i18n.py


示例17: format

 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)
开发者ID:liberapay,项目名称:liberapay.com,代码行数:34,代码来源:base.py


示例18: shopping_list_to_html5

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>'
开发者ID:bjorkegeek,项目名称:brittamat,代码行数:25,代码来源:html5.py


示例19: money_format_long

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.########')
开发者ID:unikmhz,项目名称:npui,代码行数:26,代码来源:locale.py


示例20: calculate_stats

    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
开发者ID:skorasaurus,项目名称:csvkit,代码行数:27,代码来源:csvstat.py



注:本文中的babel.numbers.format_decimal函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python numbers.format_number函数代码示例发布时间:2022-05-24
下一篇:
Python numbers.format_currency函数代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap