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


Python decimal.Decimal方法代码示例

本文整理汇总了Python中decimal.Decimal方法的典型用法代码示例。如果您正苦于以下问题:Python decimal.Decimal方法的具体用法?Python decimal.Decimal怎么用?Python decimal.Decimal使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在decimal的用法示例。


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

示例1: currency

# 需要导入模块: import decimal [as 别名]
# 或者: from decimal import Decimal [as 别名]
def currency(value, currency=None):
    """
    Format decimal value as currency
    """
    try:
        value = D(value)
    except (TypeError, InvalidOperation):
        return ""

    # Using Babel's currency formatting
    # http://babel.pocoo.org/en/latest/api/numbers.html#babel.numbers.format_currency

    kwargs = {
        'currency': currency or CURRENCY,
        'locale': to_locale(get_language() or settings.LANGUAGE_CODE)
    }

    return format_currency(value, **kwargs) 
开发者ID:slyapustin,项目名称:django-classified,代码行数:20,代码来源:classified.py

示例2: clean_value

# 需要导入模块: import decimal [as 别名]
# 或者: from decimal import Decimal [as 别名]
def clean_value(value, unit="", convert_to_percent=False, max_dgts=3):
    """return clean value with maximum digits and optional unit and percent"""
    dgts = max_dgts
    value = str(value) if not isinstance(value, six.string_types) else value
    try:
        value = Decimal(value)
        dgts = len(value.as_tuple().digits)
        dgts = max_dgts if dgts > max_dgts else dgts
    except DecimalException:
        return value
    if convert_to_percent:
        value = Decimal(value) * Decimal("100")
        unit = "%"
    val = "{{:.{}g}}".format(dgts).format(value)
    if unit:
        val += " {}".format(unit)
    return val 
开发者ID:materialsproject,项目名称:MPContribs,代码行数:19,代码来源:utils.py

示例3: get_margin

# 需要导入模块: import decimal [as 别名]
# 或者: from decimal import Decimal [as 别名]
def get_margin(price=0.0):
    """
    Returns the proper margin % for this price
    """
    price  = Decimal(price)
    margin = defaults.margin()

    try:
        return Decimal(margin)
    except Exception:
        ranges = margin.split(';')
        for r in ranges:
            m = re.search(r'(\d+)\-(\d+)=(\d+)', r)
            p_min, p_max, margin = m.groups()
            if Decimal(p_min) <= price <= Decimal(p_max):
                return Decimal(margin)

    return Decimal(margin) 
开发者ID:fpsw,项目名称:Servo,代码行数:20,代码来源:product.py

示例4: calculate_price

# 需要导入模块: import decimal [as 别名]
# 或者: from decimal import Decimal [as 别名]
def calculate_price(self, price, shipping=0.0):
        """
        Calculates price and returns it w/ and w/o tax
        """
        conf = Configuration.conf()
        shipping = shipping or 0.0

        if not isinstance(shipping, Decimal):
            shipping = Decimal(shipping)

        margin = get_margin(price)
        vat = Decimal(conf.get("pct_vat", 0.0))

        # TWOPLACES = Decimal(10) ** -2  # same as Decimal('0.01')
        # @TODO: make rounding configurable!
        wo_tax = ((price*100)/(100-margin)+shipping).to_integral_exact(rounding=ROUND_CEILING)
        with_tax = (wo_tax*(vat+100)/100).to_integral_exact(rounding=ROUND_CEILING)

        return wo_tax, with_tax 
开发者ID:fpsw,项目名称:Servo,代码行数:21,代码来源:product.py

示例5: reset_book

# 需要导入模块: import decimal [as 别名]
# 或者: from decimal import Decimal [as 别名]
def reset_book(self):
        self._asks = SortedDict()
        self._bids = SortedDict()
        res = self._client.get_product_order_book(product_id=self.product_id, level=3)
        for bid in res['bids']:
            self.add({
                'id': bid[2],
                'side': 'buy',
                'price': Decimal(bid[0]),
                'size': Decimal(bid[1])
            })
        for ask in res['asks']:
            self.add({
                'id': ask[2],
                'side': 'sell',
                'price': Decimal(ask[0]),
                'size': Decimal(ask[1])
            })
        self._sequence = res['sequence'] 
开发者ID:kkuette,项目名称:TradzQAI,代码行数:21,代码来源:order_book.py

示例6: add

# 需要导入模块: import decimal [as 别名]
# 或者: from decimal import Decimal [as 别名]
def add(self, order):
        order = {
            'id': order.get('order_id') or order['id'],
            'side': order['side'],
            'price': Decimal(order['price']),
            'size': Decimal(order.get('size') or order['remaining_size'])
        }
        if order['side'] == 'buy':
            bids = self.get_bids(order['price'])
            if bids is None:
                bids = [order]
            else:
                bids.append(order)
            self.set_bids(order['price'], bids)
        else:
            asks = self.get_asks(order['price'])
            if asks is None:
                asks = [order]
            else:
                asks.append(order)
            self.set_asks(order['price'], asks) 
开发者ID:kkuette,项目名称:TradzQAI,代码行数:23,代码来源:order_book.py

示例7: remove

# 需要导入模块: import decimal [as 别名]
# 或者: from decimal import Decimal [as 别名]
def remove(self, order):
        price = Decimal(order['price'])
        if order['side'] == 'buy':
            bids = self.get_bids(price)
            if bids is not None:
                bids = [o for o in bids if o['id'] != order['order_id']]
                if len(bids) > 0:
                    self.set_bids(price, bids)
                else:
                    self.remove_bids(price)
        else:
            asks = self.get_asks(price)
            if asks is not None:
                asks = [o for o in asks if o['id'] != order['order_id']]
                if len(asks) > 0:
                    self.set_asks(price, asks)
                else:
                    self.remove_asks(price) 
开发者ID:kkuette,项目名称:TradzQAI,代码行数:20,代码来源:order_book.py

示例8: match

# 需要导入模块: import decimal [as 别名]
# 或者: from decimal import Decimal [as 别名]
def match(self, order):
        size = Decimal(order['size'])
        price = Decimal(order['price'])

        if order['side'] == 'buy':
            bids = self.get_bids(price)
            if not bids:
                return
            assert bids[0]['id'] == order['maker_order_id']
            if bids[0]['size'] == size:
                self.set_bids(price, bids[1:])
            else:
                bids[0]['size'] -= size
                self.set_bids(price, bids)
        else:
            asks = self.get_asks(price)
            if not asks:
                return
            assert asks[0]['id'] == order['maker_order_id']
            if asks[0]['size'] == size:
                self.set_asks(price, asks[1:])
            else:
                asks[0]['size'] -= size
                self.set_asks(price, asks) 
开发者ID:kkuette,项目名称:TradzQAI,代码行数:26,代码来源:order_book.py

示例9: to_python

# 需要导入模块: import decimal [as 别名]
# 或者: from decimal import Decimal [as 别名]
def to_python(self, value):
        if not value or value == 'None':
            return None
        if isinstance(value, Places):
            return value
        if isinstance(value, list):
            return Places(value[0], value[1], value[2])

        value_parts = [Decimal(val) for val in value.split(',')[-2:]]

        try:
            latitude = value_parts[0]
        except IndexError:
            latitude = '0.0'

        try:
            longitude = value_parts[1]
        except IndexError:
            longitude = '0.0'
        try:
            place = ','.join(value.split(',')[:-2])
        except:
            pass

        return Places(place, latitude, longitude) 
开发者ID:oscarmcm,项目名称:django-places,代码行数:27,代码来源:fields.py

示例10: _get_pi

# 需要导入模块: import decimal [as 别名]
# 或者: from decimal import Decimal [as 别名]
def _get_pi(from_scratch: bool = False) -> "Decimal":
    """Get pi to 36 digits (or more with mpmath).

    Parameters
    ----------
    from_scratch : bool, optional
        If True, recomputes Pi from mpmath.

    Returns
    -------
    Decimal
        A representation of Pi
    """

    if from_scratch:  # pragma: no cover
        from mpmath import mp

        mp.dps = 36
        return mp.pi
    else:
        return Decimal("3.14159265358979323846264338327950288") 
开发者ID:MolSSI,项目名称:QCElemental,代码行数:23,代码来源:context.py

示例11: __init__

# 需要导入模块: import decimal [as 别名]
# 或者: from decimal import Decimal [as 别名]
def __init__(self, context: str = "MANTINA2009"):
        self.vdwr: Dict[str, Datum] = collections.OrderedDict()

        from .data import mantina_2009_vanderwaals_radii

        if context == "MANTINA2009":
            self.doi = mantina_2009_vanderwaals_radii["doi"]
            self.native_units = mantina_2009_vanderwaals_radii["units"]

            # TypedDict wont be in until 3.8, have to ignore heterogeneous dicts for now
            for vdwr in mantina_2009_vanderwaals_radii["vanderwaals_radii"]:  # type: ignore
                self.vdwr[vdwr[0]] = Datum(vdwr[0], self.native_units, Decimal(vdwr[1]), doi=self.doi)
        else:
            raise KeyError("Context set as '{}', only contexts {'MANTINA2009', } are currently supported")

        self.name = context
        self.year = int(mantina_2009_vanderwaals_radii["date"][:4])  # type: ignore 
开发者ID:MolSSI,项目名称:QCElemental,代码行数:19,代码来源:vanderwaals_radii.py

示例12: collect_data

# 需要导入模块: import decimal [as 别名]
# 或者: from decimal import Decimal [as 别名]
def collect_data(address_list, round, output_dir = None):
    results = []
    for a in address_list:
        req = json.dumps(common.current_balance_request(a.address))
        result = common.request(common.api_base % int(a.shard), req)
        new_entry = {"address": a.address, "shard": a.shard, "index": round}
        if result == None:
            new_entry["balance"] = dec.Decimal('NAN')
        else:
            new_entry["balance"] = common.format_balance(result["result"])
        results.append(new_entry)

    if output_dir:
        output_path = os.path.join(output_dir, timestamp.strftime("%b%d%Y_%H%M"))
        write_output(pd.DataFrame(results), output_path)
    else:
        return pd.DataFrame(results) 
开发者ID:harmony-one,项目名称:harmony-ops,代码行数:19,代码来源:collect_data.py

示例13: default

# 需要导入模块: import decimal [as 别名]
# 或者: from decimal import Decimal [as 别名]
def default(self, o):
        if types.FunctionType == type(o):
            return o.__name__
        # sets become lists
        if isinstance(o, set):
            return list(o)
        # date times become strings
        if isinstance(o, datetime):
            return o.isoformat()
        if isinstance(o, decimal.Decimal):
            return float(o)
        if isinstance(o, type):
            return str(o)
        if isinstance(o, Exception):
            return str(o)
        if isinstance(o, set):
            return str(o, 'utf-8')
        if isinstance(o, bytes):
            return str(o, 'utf-8')
        
        return json.JSONEncoder.default(self, o) 
开发者ID:awslabs,项目名称:aws-ops-automator,代码行数:23,代码来源:__init__.py

示例14: myround

# 需要导入模块: import decimal [as 别名]
# 或者: from decimal import Decimal [as 别名]
def myround(num, label=1):
    """
    correct implementation of round with round half up, round to 2 decimals

    :param num: the floating number, to be rounded
    :param label: integer 1 or 2, 1 for round half up while 2 for always round down
    :returns: the float number after rounding, with two decimals
    """
    if label == 1:
        res = float(
            Decimal(str(num)).quantize(Decimal("0.01"), rounding="ROUND_HALF_UP")
        )
    elif (
        label == 2
    ):  # for jingshunchangcheng... who just omit the overflow share behind 2 decimal
        res = float(Decimal(str(num)).quantize(Decimal("0.01"), rounding="ROUND_DOWN"))
    return res 
开发者ID:refraction-ray,项目名称:xalpha,代码行数:19,代码来源:cons.py

示例15: test_has_fields

# 需要导入模块: import decimal [as 别名]
# 或者: from decimal import Decimal [as 别名]
def test_has_fields(self):
        '''
        Initially, doing a limited test of fields as figure out how mamu of the
        CourseEnrollment model fields and relationships we need to capture.
        '''
        data = self.serializer.data

        assert data['course_id'] == str(self.model_obj.course_id)
        # assert data['course']['id'] == str(self.model_obj.course.id)
        # assert data['course']['display_name'] == self.model_obj.course.display_name
        # assert data['course']['org'] == self.model_obj.course.org

        assert dateutil_parse(data['created']) == self.model_obj.created
        assert data['user']['fullname'] == self.model_obj.user.profile.name

        for field_name in (self.expected_results_keys - self.special_fields):
            db_field = getattr(self.model_obj, field_name)
            if type(db_field) in (float, Decimal, ):
                assert float(data[field_name]) == pytest.approx(db_field)
            else:
                assert data[field_name] == db_field 
开发者ID:appsembler,项目名称:figures,代码行数:23,代码来源:test_serializers.py


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