Python decimal.ROUND_UP Examples

The following are 15 code examples of decimal.ROUND_UP(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module decimal , or try the search function .
Example #1
Source File: credit_payoffs.py    From biweeklybudget with GNU Affero General Public License v3.0 6 votes vote down vote up
def get(self):
        setting = db_session.query(DBSetting).get('credit-payoff')
        if setting is None:
            pymt_settings_json = json.dumps({'increases': [], 'onetimes': []})
        else:
            pymt_settings_json = setting.value
        pymt_settings_kwargs = self._payment_settings_dict(pymt_settings_json)
        try:
            ih = InterestHelper(db_session, **pymt_settings_kwargs)
            mps = sum(ih.min_payments.values())
            payoffs = self._payoffs_list(ih)
        except NoInterestChargedError as ex:
            resp = render_template(
                'credit-payoffs-no-interest-error.html',
                acct_name=ex.account.name,
                acct_id=ex.account.id
            )
            return resp, 500
        return render_template(
            'credit-payoffs.html',
            monthly_pymt_sum=mps.quantize(Decimal('.01'), rounding=ROUND_UP),
            payoffs=payoffs,
            pymt_settings_json=pymt_settings_json
        ) 
Example #2
Source File: dex.py    From counterblock with MIT License 6 votes vote down vote up
def calculate_price(base_quantity, quote_quantity, base_divisibility, quote_divisibility, order_type=None):
    if not base_divisibility:
        base_quantity *= config.UNIT
    if not quote_divisibility:
        quote_quantity *= config.UNIT

    try:
        if order_type == 'BUY':
            decimal.setcontext(decimal.Context(prec=8, rounding=decimal.ROUND_DOWN))
        elif order_type == 'SELL':
            decimal.setcontext(decimal.Context(prec=8, rounding=decimal.ROUND_UP))

        price = format(D(quote_quantity) / D(base_quantity), '.8f')

        decimal.setcontext(decimal.Context(prec=8, rounding=decimal.ROUND_HALF_EVEN))
        return price

    except Exception as e:
        logging.exception(e)
        decimal.setcontext(decimal.Context(prec=8, rounding=decimal.ROUND_HALF_EVEN))
        raise(e) 
Example #3
Source File: packer.py    From rectpack with Apache License 2.0 6 votes vote down vote up
def float2dec(ft, decimal_digits):
    """
    Convert float (or int) to Decimal (rounding up) with the
    requested number of decimal digits.

    Arguments:
        ft (float, int): Number to convert
        decimal (int): Number of digits after decimal point

    Return:
        Decimal: Number converted to decima
    """
    with decimal.localcontext() as ctx:
        ctx.rounding = decimal.ROUND_UP
        places = decimal.Decimal(10)**(-decimal_digits)
        return decimal.Decimal.from_float(float(ft)).quantize(places)


# Sorting algos for rectangle lists 
Example #4
Source File: account_asset.py    From LibrERP with GNU Affero General Public License v3.0 6 votes vote down vote up
def _get_depreciation_stop_date(self, cr, uid, asset, depreciation_start_date, lost_year, context=None):
        if asset.method_time == 'year':
            depreciation_stop_date = depreciation_start_date + relativedelta(years=asset.method_number, days=-1)
        elif asset.method_time == 'number':
            if asset.method_period == 'month':
                depreciation_stop_date = depreciation_start_date + relativedelta(months=asset.method_number, days=-1)
            elif asset.method_period == 'quarter':
                depreciation_stop_date = depreciation_start_date + relativedelta(months=asset.method_number * 3, days=-1)
            elif asset.method_period == 'year':
                depreciation_stop_date = depreciation_start_date + relativedelta(years=asset.method_number, days=-1)
        elif asset.method_time == 'end':
            depreciation_stop_date = datetime.strptime(asset.method_end, '%Y-%m-%d')
        elif asset.method_time == 'percent':
            if asset.method_period == 'month':
                depreciation_stop_date = depreciation_start_date + relativedelta(
                    months=int(Decimal(str(100 / asset.method_number_percent)).quantize(Decimal('1'), rounding=ROUND_UP)), days=-1)
            elif asset.method_period == 'quarter':
                depreciation_stop_date = depreciation_start_date + relativedelta(
                    months=int(Decimal(str(100 / asset.method_number_percent * 3)).quantize(Decimal('1'), rounding=ROUND_UP)), days=-1)
            elif asset.method_period == 'year':
                depreciation_stop_date = depreciation_start_date + relativedelta(
                    years=int(Decimal(str(100 / asset.method_number_percent)).quantize(Decimal('1'), rounding=ROUND_UP)) + lost_year, days=-1)
        return depreciation_stop_date 
Example #5
Source File: excellib.py    From koala with GNU General Public License v3.0 6 votes vote down vote up
def roundup(number, num_digits = 0): # Excel reference: https://support.office.com/en-us/article/ROUNDUP-function-f8bc9b23-e795-47db-8703-db171d0c42a7

    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_UP))
        # see https://docs.python.org/2/library/functions.html#round
        # and https://gist.github.com/ejamesc/cedc886c5f36e2d075c5

    else:
        return ceil(number / pow(10, -num_digits)) * pow(10, -num_digits) 
Example #6
Source File: sql_alchemy.py    From flask-profiler with MIT License 6 votes vote down vote up
def insert(self, kwds):
        endedAt = int(kwds.get('endedAt', None))
        startedAt = int(kwds.get('startedAt', None))
        elapsed = Decimal(kwds.get('elapsed', None))
        if elapsed:
            elapsed = elapsed.quantize(Decimal('.0001'), rounding=ROUND_UP)
        args = json.dumps(list(kwds.get('args', ())))  # tuple -> list -> json
        kwargs = json.dumps(kwds.get('kwargs', ()))
        context = json.dumps(kwds.get('context', {}))
        method = kwds.get('method', None)
        name = kwds.get('name', None)

        session = sessionmaker(self.db)()
        session.add(Measurements(
            endedAt=endedAt,
            startedAt=startedAt,
            elapsed=elapsed,
            args=args,
            kwargs=kwargs,
            context=context,
            method=method,
            name=name,
        ))
        session.commit() 
Example #7
Source File: randgen.py    From donation-tracker with Apache License 2.0 5 votes vote down vote up
def random_amount(rand, *, min_amount=Decimal('0.00'), max_amount=Decimal('10000.00')):
    drange = max_amount - min_amount
    return (min_amount + (drange * Decimal(rand.random()))).quantize(
        Decimal('.01'), rounding=decimal.ROUND_UP
    ) 
Example #8
Source File: fp.py    From claripy with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def pydecimal_equivalent_rounding_mode(self):
        return {
            RM.RM_TowardsPositiveInf:      decimal.ROUND_CEILING,
            RM.RM_TowardsNegativeInf:      decimal.ROUND_FLOOR,
            RM.RM_TowardsZero:             decimal.ROUND_DOWN,
            RM.RM_NearestTiesEven:         decimal.ROUND_HALF_EVEN,
            RM.RM_NearestTiesAwayFromZero: decimal.ROUND_UP,
        }[self] 
Example #9
Source File: payment.py    From tbk with GNU General Public License v3.0 5 votes vote down vote up
def clean_amount(amount):
    return decimal.Decimal(str(amount)).quantize(decimal.Decimal('.01'), rounding=decimal.ROUND_UP) 
Example #10
Source File: attrs.py    From lbry-sdk with MIT License 5 votes vote down vote up
def usd(self, amount: Decimal):
        self.pennies = int(amount.quantize(self.PENNY, ROUND_UP) * self.PENNIES) 
Example #11
Source File: utils.py    From django-konfera with MIT License 5 votes vote down vote up
def currency_round_up(money):
    return money.quantize(Decimal('1.00'), rounding=ROUND_UP) 
Example #12
Source File: __init__.py    From asgard-api with MIT License 5 votes vote down vote up
def round_up(n: Decimal, prec: int = 2) -> Decimal:
    return n.quantize(Decimal("." + "0" * prec), rounding=ROUND_UP) 
Example #13
Source File: ExchangeInfo.py    From crypto-bot with Apache License 2.0 5 votes vote down vote up
def adjust_quanity(self, q, round_down=True):
        if q == 0:
            return 0

        res = float(Decimal(q).quantize(self.stepSize, rounding=ROUND_DOWN if round_down else ROUND_UP))
        return float(min(max(res, self.minQty), self.maxQty)) 
Example #14
Source File: ExchangeInfo.py    From crypto-bot with Apache License 2.0 5 votes vote down vote up
def adjust_price(self, q, round_down=True):
        res = round(Decimal(q), 8)

        if self.tickSize:  # if tickSize Enabled
            res = res.quantize(self.tickSize, rounding=ROUND_DOWN if round_down else ROUND_UP)

        if self.minPrice:  # if minPrice Enabled
            res = max(res, self.minPrice)

        if self.maxPrice:  # if minPrice Enabled
            res = min(res, self.maxPrice)

        return float(res) 
Example #15
Source File: randgen.py    From donation-tracker with Apache License 2.0 4 votes vote down vote up
def generate_donation(
    rand,
    *,
    donor=None,
    domain=None,
    event=None,
    min_amount=Decimal('0.01'),
    max_amount=Decimal('1000.00'),
    min_time=None,
    max_time=None,
    donors=None,
    transactionstate=None,
):
    donation = Donation()
    donation.amount = random_amount(rand, min_amount=min_amount, max_amount=max_amount)
    if event:
        donation.event = event
    else:
        donation.event = pick_random_instance(rand, Event)
    if domain:
        donation.domain = domain
    else:
        donation.domain = pick_random_element(rand, DonationDomainChoices)[0]
    donation.domainId = str(rand.getrandbits(64))
    donation.fee = (donation.amount * Decimal(0.03)).quantize(
        Decimal('0.01'), rounding=decimal.ROUND_UP
    )
    donation.comment = random_name(rand, 'Comment')
    donation.commentstate = 'APPROVED'
    donation.readstate = 'READ'
    if not min_time:
        min_time = event.datetime
    if not max_time:
        max_time = min_time + datetime.timedelta(seconds=60 * 60 * 24 * 14)
    donation.timereceived = random_time(rand, min_time, max_time)
    donation.currency = 'USD'
    donation.transactionstate = transactionstate or 'COMPLETED'
    if donation.domain == 'LOCAL':
        assert donation.transactionstate == 'COMPLETED'

    if not donor:
        if donors:
            donor = pick_random_element(rand, donors)
        else:
            donor = pick_random_instance(rand, Donor)
    if not donor:  # no provided donors at all
        donor = generate_donor(rand)
        donor.save()
    donation.donor = donor
    donation.clean()
    return donation