当前位置: 首页>>代码示例>>Python>>正文


Python numbers.parse_decimal函数代码示例

本文整理汇总了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
开发者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


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