本文整理汇总了Python中babel.numbers.parse_decimal函数的典型用法代码示例。如果您正苦于以下问题:Python parse_decimal函数的具体用法?Python parse_decimal怎么用?Python parse_decimal使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了parse_decimal函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: test
def test(self, d):
"""
Test, for purposes of type inference, if a value could possibly be valid
for this column type. This will work with values that are native types
and values that have been stringified.
"""
if d is None:
return True
if isinstance(d, Decimal):
return True
if type(d) is int or type(d) is float:
return True
if not isinstance(d, six.string_types):
return False
d = d.strip()
d = d.strip('%')
for symbol in CURRENCY_SYMBOLS:
d = d.strip(symbol)
if d.lower() in self.null_values:
return True
try:
parse_decimal(d, self._locale)
return True
except:
return False
开发者ID:nsonnad,项目名称:agate,代码行数:32,代码来源:number.py
示例2: test_can_parse_decimals
def test_can_parse_decimals(self):
self.assertEqual(decimal.Decimal('1099.98'),
numbers.parse_decimal('1,099.98', locale='en_US'))
self.assertEqual(decimal.Decimal('1099.98'),
numbers.parse_decimal('1.099,98', locale='de'))
self.assertRaises(numbers.NumberFormatError,
lambda: numbers.parse_decimal('2,109,998', locale='de'))
开发者ID:gmist,项目名称:babel,代码行数:7,代码来源:test_numbers.py
示例3: test_parse_decimal
def test_parse_decimal():
assert (numbers.parse_decimal('1,099.98', locale='en_US')
== decimal.Decimal('1099.98'))
assert numbers.parse_decimal('1.099,98', locale='de') == decimal.Decimal('1099.98')
with pytest.raises(numbers.NumberFormatError) as excinfo:
numbers.parse_decimal('2,109,998', locale='de')
assert excinfo.value.args[0] == "'2,109,998' is not a valid decimal number"
开发者ID:gmist,项目名称:babel,代码行数:8,代码来源:test_numbers.py
示例4: hydrate_total_value
def hydrate_total_value(self, bundle):
value = bundle.data.get('total_value', None)
if value:
bundle.data['total_value'] = parse_decimal(str(value), locale=bundle.request.locale)
return bundle
开发者ID:marcio0,项目名称:niqels,代码行数:7,代码来源:split_transaction_resource.py
示例5: execute
def execute(self, table_id, select_index, aggregation_index, conditions, lower=True):
if not table_id.startswith('table'):
table_id = 'table_{}'.format(table_id.replace('-', '_'))
table_info = self.db.query('SELECT sql from sqlite_master WHERE tbl_name = :name', name=table_id).all()[0].sql
schema_str = schema_re.findall(table_info)[0]
schema = {}
for tup in schema_str.split(', '):
c, t = tup.split()
schema[c] = t
select = 'col{}'.format(select_index)
agg = Query.agg_ops[aggregation_index]
if agg:
select = '{}({})'.format(agg, select)
where_clause = []
where_map = {}
for col_index, op, val in conditions:
if lower and isinstance(val, str):
val = val.lower()
if schema['col{}'.format(col_index)] == 'real' and not isinstance(val, (int, float)):
try:
val = float(parse_decimal(val))
except NumberFormatError as e:
val = float(num_re.findall(val)[0])
where_clause.append('col{} {} :col{}'.format(col_index, Query.cond_ops[op], col_index))
where_map['col{}'.format(col_index)] = val
where_str = ''
if where_clause:
where_str = 'WHERE ' + ' AND '.join(where_clause)
query = 'SELECT {} AS result FROM {} {}'.format(select, table_id, where_str)
out = self.db.query(query, **where_map)
return [o.result for o in out]
开发者ID:chubbymaggie,项目名称:tranX,代码行数:31,代码来源:dbengine.py
示例6: cast
def cast(self, d):
"""
Cast a single value to a :class:`decimal.Decimal`.
:returns: :class:`decimal.Decimal` or :code:`None`.
:raises: :exc:`.CastError`
"""
if isinstance(d, Decimal) or d is None:
return d
elif isinstance(d, int):
return Decimal(d)
elif isinstance(d, float):
raise CastError('Can not convert float to Decimal. Convert data to string first!')
elif isinstance(d, six.string_types):
d = d.strip()
d = d.strip('%')
for symbol in CURRENCY_SYMBOLS:
d = d.strip(symbol)
if d.lower() in self.null_values:
return None
try:
return parse_decimal(d, self._locale)
except:
raise CastError('Can not parse value "%s" as Decimal.' % d)
开发者ID:nickdudaev,项目名称:agate,代码行数:27,代码来源:number.py
示例7: parse_decimal
def parse_decimal(string, locale=None):
"""Parses localized decimal string into a float.
.. code-block:: python
>>> parse_decimal('1,099.98', locale='en_US')
1099.98
>>> parse_decimal('1.099,98', locale='de')
1099.98
When the given string cannot be parsed, an exception is raised:
.. code-block:: python
>>> parse_decimal('2,109,998', locale='de')
Traceback (most recent call last):
...
NumberFormatError: '2,109,998' is not a valid decimal number
:param string:
The string to parse.
:param locale:
A locale code. If not set, uses the currently loaded locale.
:returns:
The parsed decimal number.
:raises:
``NumberFormatError`` if the string can not be converted to a
decimal number.
"""
locale = locale or get_locale()
return numbers.parse_decimal(string, locale=locale)
开发者ID:Hubble1,项目名称:eventgrinder,代码行数:31,代码来源:i18n.py
示例8: parse_value
def parse_value(value):
"""
Accepts a string value and attempts to parce it as a currency value.
Returns the extracted numeric value converted to a string
"""
l_currency_language_code, l_currency_code = _getCodes()
curSym = get_currency_symbol(l_currency_code, l_currency_language_code)
grpSym = get_group_symbol(locale=l_currency_language_code.lower())
decSym = get_decimal_symbol(locale=l_currency_language_code.lower())
# Convert the Official characters into what comes from the keyboard.
# This section may need to grow over time.
# - Character 160 is a non-breaking space, which is different from a typed space
if ord(grpSym) == 160:
value = value.replace(u" ", grpSym)
allSym = _getSymbols(value)
invalidSym = allSym.replace(curSym, "").replace(grpSym, "").replace(decSym, "").replace(u"-", "")
value = value.replace(curSym, "")
if allSym.count(decSym) > 1:
raise NumberFormatError(default_error_messages["decimal_symbol"] % decSym)
elif (allSym.count(decSym) == 1 and allSym[-1] != decSym) or len(invalidSym) > 0:
raise NumberFormatError(default_error_messages["invalid_format"] % (grpSym, decSym))
elif value.count(decSym) == 1:
value = parse_decimal(value, locale=l_currency_language_code.lower())
else:
value = parse_number(value, locale=l_currency_language_code.lower())
# The value is converted into a string because the parse functions return
# floats
return str(value)
开发者ID:aweakley,项目名称:django-admin-steroids,代码行数:35,代码来源:fields.py
示例9: cast
def cast(self, d):
"""
Cast a single value to a :class:`decimal.Decimal`.
:returns:
:class:`decimal.Decimal` or :code:`None`.
"""
if isinstance(d, Decimal) or d is None:
return d
elif type(d) is int:
return Decimal(d)
elif type(d) is float:
return Decimal(self.float_format % d)
elif isinstance(d, six.string_types):
d = d.strip()
d = d.strip("%")
for symbol in CURRENCY_SYMBOLS:
d = d.strip(symbol)
if d.lower() in self.null_values:
return None
else:
raise CastError('Can not parse value "%s" as Decimal.' % d)
try:
return parse_decimal(d, self.locale)
except:
pass
raise CastError('Can not parse value "%s" as Decimal.' % d)
开发者ID:RippowamLabs,项目名称:agate,代码行数:31,代码来源:number.py
示例10: asValue
def asValue(self, strValue, objType):
'''
@see: Converter.asValue
'''
assert isinstance(objType, Type), 'Invalid object type %s' % objType
if strValue is None: return None
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 strValue
if objType.isOf(Boolean):
return strValue.strip().lower() == _('true').lower()
if objType.isOf(Percentage):
return float(strValue) / 100
if objType.isOf(int):
return int(strValue)
if objType.isOf(Number):
return bn.parse_decimal(strValue, self.locale)
if objType.isOf(Date):
return datetime.strptime(strValue, '%Y-%m-%d').date()
if objType.isOf(Time):
return datetime.strptime(strValue, '%H:%M:%S').time()
if objType.isOf(DateTime):
return datetime.strptime(strValue, '%Y-%m-%d %H:%M:%S')
raise TypeError('Invalid object type %s for Babel converter' % objType)
开发者ID:ahilles107,项目名称:Superdesk,代码行数:28,代码来源:text_conversion.py
示例11: clean
def clean(self, value):
locale=get_current_language()
if value != "":
try:
value = force_unicode(parse_decimal(value, locale=locale))
except NumberFormatError:
raise forms.ValidationError(self.error_messages['invalid'])
return super(FloatField, self).clean(value)
开发者ID:archatas,项目名称:django-base-libs,代码行数:8,代码来源:fields.py
示例12: normalize_field
def normalize_field(self, value):
if isinstance(value, (int, float)):
return value
if value == '':
value = None
elif value is not None:
value = float(parse_decimal(value, locale=settings.get_locale()))
return super(FloatField, self).normalize_field(value)
开发者ID:renzon,项目名称:gaeforms,代码行数:8,代码来源:base.py
示例13: test
def test(self, d):
"""
Test, for purposes of type inference, if a string value could possibly
be valid for this column type.
"""
d = d.strip()
d = d.strip('%')
for symbol in CURRENCY_SYMBOLS:
d = d.strip(symbol)
if d.lower() in self.null_values:
return True
try:
parse_decimal(d, self._locale)
return True
except:
return False
开发者ID:TylerFisher,项目名称:agate,代码行数:19,代码来源:number.py
示例14: localize_money
def localize_money(money, currency=None, language=None):
if language is None:
language = preferred_language()
if not isinstance(money, Decimal):
money = parse_decimal(money)
if currency:
return format_currency(money, currency, locale=language)
else:
return format_decimal(money, locale=language, format="#,##0.00")
开发者ID:deti,项目名称:boss,代码行数:11,代码来源:i18n.py
示例15: _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
示例16: parse_decimal
def parse_decimal(value):
if isinstance(value, basestring):
value = ustr(value)
#deal with ' ' instead of u'\xa0' (SP instead of NBSP as grouping char)
value = value.replace(' ', '')
try:
value = numbers.parse_decimal(value, locale=get_locale())
except ValueError, e:
pass
开发者ID:KDVN,项目名称:KDINDO.OpenERP,代码行数:12,代码来源:format.py
示例17: color_scale
def color_scale(name, text):
# filter out everything that does not seem to be necessary to interpret the string as a number
# this permits to transform "[ 95%]" to "95" before number conversion,
# and thus allows to color a group larger than the matched number
chars_in_numbers = "-+.,e/*"
allowed = string.digits + chars_in_numbers
nb = "".join([i for i in filter(allowed.__contains__, text)])
# interpret as decimal
# First, try with the babel module, if available
# if not, use python itself,
# if thoses fails, try to `eval` the string
# (this allow strings like "1/2+0.9*2")
f = None
try:
# babel is a specialized module
import babel.numbers as bn
try:
f = float(bn.parse_decimal(nb))
except bn.NumberFormatError:
pass
except ImportError:
try:
f = float(nb)
except ValueError:
pass
if f is not None:
# normalize with scale if it's a number
f = (f - context["scale"][0]) / (context["scale"][1] - context["scale"][0])
else:
# interpret as float between 0 and 1 otherwise
f = eval(nb)
# if out of scale, do not color
if f < 0 or f > 1:
return None
# normalize and scale over the nb of colors in cmap
colormap = context["colormaps"][name]
i = int(math.ceil(f * (len(colormap) - 1)))
color = colormap[i]
# infer mode from the color in the colormap
m = mode(color)
if m == 8:
color_code = str(30 + context["colors"][color])
else:
color_code = str(color)
return color_code
开发者ID:bbxfork,项目名称:colout,代码行数:52,代码来源:colout.py
示例18: render
def render(self, name, value, attrs=None):
from babel.numbers import parse_decimal
from babel.numbers import format_decimal
from babel.numbers import NumberFormatError
locale=get_current_language()
if value is None: value = ""
if value and isinstance(value, basestring):
try:
value = parse_decimal(value, locale=locale)
except NumberFormatError:
pass
if value is not "" and not isinstance(value, basestring):
value = format_decimal(value, self.format, locale=locale)
return super(DecimalWidget, self).render(name, value, attrs)
开发者ID:archatas,项目名称:django-base-libs,代码行数:14,代码来源:widgets.py
示例19: add_helpers_to_context
def add_helpers_to_context(tell_sentry, context, loc, request=None):
context['locale'] = loc
context['decimal_symbol'] = get_decimal_symbol(locale=loc)
context['_'] = lambda s, *a, **kw: get_text(loc, s, *a, **kw)
context['ngettext'] = lambda *a, **kw: n_get_text(tell_sentry, request, loc, *a, **kw)
context['format_number'] = lambda *a: format_number(*a, locale=loc)
context['format_decimal'] = lambda *a: format_decimal(*a, locale=loc)
context['format_currency'] = lambda *a, **kw: format_currency_with_options(*a, locale=loc, **kw)
context['format_percent'] = lambda *a: format_percent(*a, locale=loc)
context['parse_decimal'] = lambda *a: parse_decimal(*a, locale=loc)
def _to_age(delta):
try:
return to_age(delta, loc)
except:
return to_age(delta, 'en')
context['to_age'] = _to_age
开发者ID:beerm,项目名称:gratipay.com,代码行数:16,代码来源:i18n.py
示例20: parse_decimal
def parse_decimal(self, string):
"""Parse localized decimal string into a float
>>> Locale('en', 'US').parse_decimal('1,099.98')
1099.98
>>> Locale('de').parse_decimal('1.099,98')
1099.98
When the given string cannot be parsed, an exception is raised:
>>> Locale('de').parse_decimal('2,109,998')
Traceback (most recent call last):
...
NumberFormatError: '2,109,998' is not a valid decimal number
"""
return numbers.parse_decimal(string, self)
开发者ID:nagareproject,项目名称:core,代码行数:16,代码来源:i18n.py
注:本文中的babel.numbers.parse_decimal函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论