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