当前位置: 首页>>代码示例>>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;未经允许,请勿转载。