本文整理汇总了Python中babel.numbers.format_decimal函数的典型用法代码示例。如果您正苦于以下问题:Python format_decimal函数的具体用法?Python format_decimal怎么用?Python format_decimal使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了format_decimal函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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)
示例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')
示例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
示例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')
示例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'
示例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)
示例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)
示例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'))
示例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')
示例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})
示例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)
示例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)
示例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)
示例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)
示例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)