當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。