當前位置: 首頁>>代碼示例>>Python>>正文


Python decimal.ROUND_HALF_UP屬性代碼示例

本文整理匯總了Python中decimal.ROUND_HALF_UP屬性的典型用法代碼示例。如果您正苦於以下問題:Python decimal.ROUND_HALF_UP屬性的具體用法?Python decimal.ROUND_HALF_UP怎麽用?Python decimal.ROUND_HALF_UP使用的例子?那麽, 這裏精選的屬性代碼示例或許可以為您提供幫助。您也可以進一步了解該屬性所在decimal的用法示例。


在下文中一共展示了decimal.ROUND_HALF_UP屬性的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: _decimalize

# 需要導入模塊: import decimal [as 別名]
# 或者: from decimal import ROUND_HALF_UP [as 別名]
def _decimalize(v, q = None):
    # If already a decimal, just return itself
    if type(v) == Decimal:
        return v

    # If tuple/list passed, bulk-convert
    elif isinstance(v, (tuple, list)):
        return type(v)(decimalize(x, q) for x in v)

    # Convert int-like
    elif isinstance(v, numbers.Integral):
        return Decimal(int(v))

    # Convert float-like
    elif isinstance(v, numbers.Real):
        if q != None:
            return Decimal(repr(v)).quantize(Decimal(repr(q)),
                rounding=ROUND_HALF_UP)
        else:
            return Decimal(repr(v))
    else:
        raise ValueError("Cannot convert {0} to Decimal.".format(v)) 
開發者ID:jsvine,項目名稱:pdfplumber,代碼行數:24,代碼來源:utils.py

示例2: _index_preshot

# 需要導入模塊: import decimal [as 別名]
# 或者: from decimal import ROUND_HALF_UP [as 別名]
def _index_preshot(self):
        logger.info('Index preshot')
        # BEGIN DB update
        conn = engine.connect()
        data_sess = scoped_session(
            sessionmaker(autocommit=False, autoflush=False, bind=conn)
        )
        for acct in data_sess.query(Account).all():
            end_bal = acct.balance.ledger
            pctrange = float(end_bal) * 0.1
            for i in range(1, 30):
                dt = dtnow() - timedelta(days=i)
                b = end_bal + Decimal(uniform(-1 * pctrange, pctrange))
                b = Decimal(b.quantize(Decimal('.001'), rounding=ROUND_HALF_UP))
                acct.set_balance(ledger=b, ledger_date=dt, overall_date=dt)
        data_sess.flush()
        data_sess.commit()
        data_sess.close()
        conn.close()
        # END DB update
        self.get('/')
        sleep(1) 
開發者ID:jantman,項目名稱:biweeklybudget,代碼行數:24,代碼來源:make_screenshots.py

示例3: get_asset_value_with_ind_tax

# 需要導入模塊: import decimal [as 別名]
# 或者: from decimal import ROUND_HALF_UP [as 別名]
def get_asset_value_with_ind_tax(self, cr, uid, vals, context):
        account_tax_obj = self.pool['account.tax']
        if not vals.get('tax_code_id', False):
            return vals['debit'] or - vals['credit']
        tax_code = self.pool['account.tax.code'].browse(cr, uid, [vals.get('tax_code_id')])[0]
        tax = tax_code.base_tax_ids
        if vals.get('quantity') == 0.0:
            quantity = 1.0
        else:
            quantity = vals.get('quantity')
            
        res = account_tax_obj.compute_all(cr, uid, taxes=tax,
            price_unit=abs(vals.get('tax_amount') / quantity),
            quantity=quantity)
        tax_list = res['taxes']
        ind_amount = 0.0
        if len(tax_list) == 2:
            for tax in tax_list:
                if tax.get('balance', False):
                    ind_tax = tax_list[abs(tax_list.index(tax) - 1)]
                    ind_amount = float(Decimal(str(ind_tax['amount'])).quantize(Decimal('1.00'), rounding=ROUND_HALF_UP))
        asset_value = vals['debit'] + ind_amount or - vals['credit'] - ind_amount
        return asset_value 
開發者ID:iw3hxn,項目名稱:LibrERP,代碼行數:25,代碼來源:account_move.py

示例4: xround

# 需要導入模塊: import decimal [as 別名]
# 或者: from decimal import ROUND_HALF_UP [as 別名]
def xround(number, num_digits = 0): # Excel reference: https://support.office.com/en-us/article/ROUND-function-c018c5d8-40fb-4053-90b1-b3e7f61a213c

    if not is_number(number):
        return ExcelError('#VALUE!', '%s is not a number' % str(number))
    if not is_number(num_digits):
        return ExcelError('#VALUE!', '%s is not a number' % str(num_digits))

    number = float(number) # if you don't Spreadsheet.dump/load, you might end up with Long numbers, which Decimal doesn't accept

    if num_digits >= 0: # round to the right side of the point
        return float(Decimal(repr(number)).quantize(Decimal(repr(pow(10, -num_digits))), rounding=ROUND_HALF_UP))
        # see https://docs.python.org/2/library/functions.html#round
        # and https://gist.github.com/ejamesc/cedc886c5f36e2d075c5

    else:
        return round(number, num_digits) 
開發者ID:vallettea,項目名稱:koala,代碼行數:18,代碼來源:excellib.py

示例5: nearest_price

# 需要導入模塊: import decimal [as 別名]
# 或者: from decimal import ROUND_HALF_UP [as 別名]
def nearest_price(price, cutoffs=CUTOFFS):
    """Returns the nearest Betfair odds value to price.

    Adapted from Anton Zemlyanov's AlgoTrader project (MIT licensed).
    https://github.com/AlgoTrader/betfair-sports-api/blob/master/lib/betfair_price.js

    :param float price: Approximate Betfair price (i.e. decimal odds value)
    :param tuple cutoffs: Optional tuple of (cutoff, step) pairs
    :returns: The nearest Befair price
    :rtype: float
    """
    if price <= MIN_PRICE:
        return MIN_PRICE
    if price > MAX_PRICE:
        return MAX_PRICE

    price = as_dec(price)
    for cutoff, step in cutoffs:
        if price < cutoff:
            break
    step = as_dec(step)
    return float((price * step).quantize(2, ROUND_HALF_UP) / step) 
開發者ID:jmcarp,項目名稱:betfair.py,代碼行數:24,代碼來源:price.py

示例6: convert_decimal

# 需要導入模塊: import decimal [as 別名]
# 或者: from decimal import ROUND_HALF_UP [as 別名]
def convert_decimal(numeric):
    full_decimal = Decimal(numeric)
    _, digits, exponent = full_decimal.as_tuple()
    # Round to MAX_DECIMAL_PLACES, if result has more places than that.
    if exponent < -MAX_DECIMAL_PLACES:
        # quantize can raise `decimal.InvalidOperation` if result is greater
        # than context precision, which is 28 by default. to get around this,
        # temporarily set a new precision up to the max number of sig figs  of
        # `full_decimal`, which is also the max for the result of `quantize`.
        # this ensures that the result of `quantize` will be within the precision
        # limit, and not raise the error.
        with localcontext() as ctx:
            ctx.prec = max(len(digits), getcontext().prec)
            return full_decimal.quantize(_PLACES_VALUE, rounding=ROUND_HALF_UP)
    else:
        return full_decimal 
開發者ID:Yelp,項目名稱:clusterman,代碼行數:18,代碼來源:misc.py

示例7: default

# 需要導入模塊: import decimal [as 別名]
# 或者: from decimal import ROUND_HALF_UP [as 別名]
def default(self, o):
        if isinstance(o, Decimal):
            return float(o.quantize(Decimal('.0001'), rounding=ROUND_HALF_UP))
        return super(DecimalEncoder, self).default(o) 
開發者ID:jsvine,項目名稱:pdfplumber,代碼行數:6,代碼來源:cli.py

示例8: um2mm

# 需要導入模塊: import decimal [as 別名]
# 或者: from decimal import ROUND_HALF_UP [as 別名]
def um2mm(length: Decimal, prec: int) -> Decimal:
    """
    Convert a length in microns to millimeters with rounding.

    :param length: The input length in microns
    :param prec: The number of digits after the decimal place to use
    :return: A length in millimeters
    """
    with decimal.localcontext() as c:
        c.rounding = decimal.ROUND_HALF_UP
        mm = length/Decimal(1000)
        p = c.power(10, prec)
        # I would use .quantize(...) here, but it doesn't seem to work for quantization values > 1 (only 1, .1, .01, ...)
        return (mm*p).to_integral_exact()/p 
開發者ID:ucb-bar,項目名稱:hammer,代碼行數:16,代碼來源:__init__.py

示例9: round_up

# 需要導入模塊: import decimal [as 別名]
# 或者: from decimal import ROUND_HALF_UP [as 別名]
def round_up(x):
    return float(Decimal(x).quantize(0, rounding=ROUND_HALF_UP)) 
開發者ID:vinci1it2000,項目名稱:formulas,代碼行數:4,代碼來源:math.py

示例10: test_query_instance_types_with_totals

# 需要導入模塊: import decimal [as 別名]
# 或者: from decimal import ROUND_HALF_UP [as 別名]
def test_query_instance_types_with_totals(self):
        """Test execute_query() - instance types with totals.

        Query for instance_types, validating that cost totals are present.

        """
        url = "?filter[time_scope_units]=month&filter[time_scope_value]=-1&filter[resolution]=monthly&group_by[instance_type]=*"  # noqa: E501
        query_params = self.mocked_query_params(url, OCPAzureInstanceTypeView)
        handler = OCPAzureReportQueryHandler(query_params)
        query_output = handler.execute_query()
        data = query_output.get("data")
        self.assertIsNotNone(data)

        for data_item in data:
            instance_types = data_item.get("instance_types")
            for it in instance_types:
                self.assertIsNotNone(it.get("values"))
                self.assertGreater(len(it.get("values")), 0)
                for value in it.get("values"):
                    self.assertIsInstance(value.get("cost", {}).get("total", {}).get("value"), Decimal)
                    self.assertGreaterEqual(
                        value.get("cost", {}).get("total", {}).get("value").quantize(Decimal(".0001"), ROUND_HALF_UP),
                        Decimal(0),
                    )
                    # FIXME: usage doesn't have units yet. waiting on MSFT
                    # self.assertIsInstance(value.get('usage', {}).get('value'), Decimal)
                    # self.assertGreater(value.get('usage', {}).get('value'), Decimal(0))
                    self.assertIsInstance(value.get("usage", {}), dict)
                    self.assertGreaterEqual(
                        value.get("usage", {}).get("value", {}).quantize(Decimal(".0001"), ROUND_HALF_UP), Decimal(0)
                    ) 
開發者ID:project-koku,項目名稱:koku,代碼行數:33,代碼來源:test_ocp_azure_query_handler.py

示例11: test_query_instance_types_with_totals

# 需要導入模塊: import decimal [as 別名]
# 或者: from decimal import ROUND_HALF_UP [as 別名]
def test_query_instance_types_with_totals(self):
        """Test execute_query() - instance types with totals.

        Query for instance_types, validating that cost totals are present.

        """
        url = "?filter[time_scope_units]=month&filter[time_scope_value]=-1&filter[resolution]=monthly&group_by[instance_type]=*"  # noqa: E501
        query_params = self.mocked_query_params(url, AzureInstanceTypeView)
        handler = AzureReportQueryHandler(query_params)
        query_output = handler.execute_query()
        data = query_output.get("data")
        self.assertIsNotNone(data)

        for data_item in data:
            instance_types = data_item.get("instance_types")
            for it in instance_types:
                self.assertIsNotNone(it.get("values"))
                self.assertGreater(len(it.get("values")), 0)
                for value in it.get("values"):
                    cost_value = value.get("cost", {}).get("total", {}).get("value")
                    self.assertIsNotNone(cost_value)
                    self.assertIsInstance(cost_value, Decimal)
                    self.assertGreaterEqual(cost_value.quantize(Decimal(".0001"), ROUND_HALF_UP), Decimal(0))
                    # FIXME: usage doesn't have units yet. waiting on MSFT
                    # self.assertIsInstance(value.get('usage', {}).get('value'), Decimal)
                    # self.assertGreater(value.get('usage', {}).get('value'), Decimal(0))
                    self.assertIsInstance(value.get("usage", {}), dict)
                    self.assertGreaterEqual(
                        value.get("usage", {}).get("value", {}).quantize(Decimal(".0001"), ROUND_HALF_UP), Decimal(0)
                    ) 
開發者ID:project-koku,項目名稱:koku,代碼行數:32,代碼來源:tests_azure_query_handler.py

示例12: quantize

# 需要導入模塊: import decimal [as 別名]
# 或者: from decimal import ROUND_HALF_UP [as 別名]
def quantize(value, rounding=decimal.ROUND_HALF_UP):
    """ 強製轉換為兩位小數類型。quantize value to two digits decimal.

    Examples::

        price_list = [(5.25, 3.33), (6.98, 3.14)]
        sales_volume = sum(quantize(unit_price * amount) for unit_price, amount in price_list)

    :rtype: decimal.Decimal
    """
    return decimal.Decimal(value).quantize(decimal.Decimal(".01"), rounding=rounding) 
開發者ID:zaihui,項目名稱:hutils,代碼行數:13,代碼來源:data_types.py

示例13: _add_transactions

# 需要導入模塊: import decimal [as 別名]
# 或者: from decimal import ROUND_HALF_UP [as 別名]
def _add_transactions(self, data_sess, pp):
        budgets = list(data_sess.query(Budget).filter(
            Budget.is_active.__eq__(True),
            Budget.is_income.__eq__(False),
            Budget.is_periodic.__eq__(True)
        ).all())
        target = 1950
        total = 0
        count = 0
        while total < target:
            count += 1
            amt = uniform(0, target * 0.2)
            if total + amt > target:
                amt = target - total
            total += amt
            amt = Decimal(Decimal(amt).quantize(
                Decimal('.001'), rounding=ROUND_HALF_UP
            ))
            data_sess.add(Transaction(
                account_id=1,
                budgeted_amount=amt,
                date=pp.start_date + timedelta(days=randrange(0, 12)),
                description='Transaction %d' % count,
                budget_amounts={
                    choice(budgets): amt
                }
            ))
            data_sess.flush()
            data_sess.commit() 
開發者ID:jantman,項目名稱:biweeklybudget,代碼行數:31,代碼來源:make_screenshots.py

示例14: _getBpm

# 需要導入模塊: import decimal [as 別名]
# 或者: from decimal import ROUND_HALF_UP [as 別名]
def _getBpm(self):
        from decimal import Decimal, ROUND_HALF_UP, InvalidOperation

        bpm = None
        if frames.BPM_FID in self.frame_set:
            bpm_str = self.frame_set[frames.BPM_FID][0].text or "0"
            try:
                # Round floats since the spec says this is an integer. Python3
                # changed how 'round' works, hence the using of decimal
                bpm = int(Decimal(bpm_str).quantize(1, ROUND_HALF_UP))
            except (InvalidOperation, ValueError) as ex:
                log.warning(ex)
        return bpm 
開發者ID:nicfit,項目名稱:eyeD3,代碼行數:15,代碼來源:tag.py

示例15: quantize

# 需要導入模塊: import decimal [as 別名]
# 或者: from decimal import ROUND_HALF_UP [as 別名]
def quantize(float, precision):
    return Decimal(float).quantize(precision, rounding=ROUND_HALF_UP) 
開發者ID:fmerg,項目名稱:pymerkle,代碼行數:4,代碼來源:__main__.py


注:本文中的decimal.ROUND_HALF_UP屬性示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。