Python decimal.ROUND_DOWN Examples

The following are 30 code examples of decimal.ROUND_DOWN(). 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: util.py    From i-cant-believe-its-not-stake with MIT License 6 votes vote down vote up
def make_change(from_node, amount_in, amount_out, fee):
    """
    Create change output(s), return them
    """
    outputs = {}
    amount = amount_out + fee
    change = amount_in - amount
    if change > amount * 2:
        # Create an extra change output to break up big inputs
        change_address = from_node.getnewaddress()
        # Split change in two, being careful of rounding:
        outputs[change_address] = Decimal(change / 2).quantize(Decimal('0.00000001'), rounding=ROUND_DOWN)
        change = amount_in - amount - outputs[change_address]
    if change > 0:
        outputs[from_node.getnewaddress()] = change
    return outputs 
Example #2
Source File: rates.py    From bit with MIT License 6 votes vote down vote up
def satoshi_to_currency_cached(num, currency):
    """Converts a given number of satoshi to another currency as a formatted
    string rounded down to the proper number of decimal places. Results are
    cached using a decorator for 60 seconds by default. See :ref:`cache times`.

    :param num: The number of satoshi.
    :type num: ``int``
    :param currency: One of the :ref:`supported currencies`.
    :type currency: ``str``
    :rtype: ``str``
    """
    return '{:f}'.format(
        Decimal(num / Decimal(currency_to_satoshi_cached(1, currency)))
        .quantize(Decimal('0.' + '0' * CURRENCY_PRECISION[currency]), rounding=ROUND_DOWN)
        .normalize()
    ) 
Example #3
Source File: views.py    From coursys with GNU General Public License v3.0 6 votes vote down vote up
def _fallout_report_data(request, start_date, end_date):
    sub_unit_ids = Unit.sub_unit_ids(request.units)
    fac_roles = Role.objects.filter(role='FAC', unit__id__in=sub_unit_ids).select_related('person', 'unit')
    table = []
    tot_fallout = 0
    for role in fac_roles:
        unit = role.unit
        p = role.person
        salary = FacultySummary(p).salary(end_date, units=[unit])
        salary_events = CareerEvent.objects.approved().overlaps_daterange(start_date, end_date) \
            .filter(person=p, unit=unit, flags=CareerEvent.flags.affects_salary)
        for event in salary_events:
            if event.event_type == 'LEAVE' or event.event_type == 'STUDYLEAVE':
                days = event.get_duration_within_range(start_date, end_date)
                fraction = FacultySummary(p).salary_event_info(event)[1]
                d = fraction.denominator
                n = fraction.numerator
                fallout = Decimal((salary - salary*n/d)*days/365).quantize(Decimal('.01'), rounding=ROUND_DOWN)
                tot_fallout += fallout

                table += [(unit.label, p, event, event.start_date, event.end_date, days, salary, fraction, fallout)]
    return table 
Example #4
Source File: formulas.py    From QRL with MIT License 6 votes vote down vote up
def remaining_emission(block_n, dev_config: DevConfig) -> Decimal:
    # TODO: This is more related to the way QRL works.. Move to another place
    """
    calculate remaining emission at block_n: N=total initial coin supply, coeff = decay constant
    need to use decimal as floating point not precise enough on different platforms..
    :param block_n:
    :return:

    >>> from qrl.core import config
    >>> remaining_emission(0, config.dev)
    Decimal('40000000000000000')
    >>> remaining_emission(1, config.dev)
    Decimal('39999993343650538')
    >>> remaining_emission(2, config.dev)
    Decimal('39999986687302185')
    >>> remaining_emission(100, config.dev)
    Decimal('39999334370536850')
    """
    coeff = calc_coeff(dev_config)
    return (dev_config.coin_remaining_at_genesis * dev_config.shor_per_quanta * Decimal(-coeff * block_n).exp()) \
        .quantize(Decimal('1.'), rounding=decimal.ROUND_DOWN) 
Example #5
Source File: quantity.py    From tensortrade with Apache License 2.0 6 votes vote down vote up
def contain(self, exchange_pair: 'ExchangePair'):
        options = exchange_pair.exchange.options
        price = exchange_pair.price

        if exchange_pair.pair.base == self.instrument:
            size = self.size
            return Quantity(self.instrument, min(size, options.max_trade_size), self.path_id)

        size = self.size * price
        if size < options.max_trade_size:
            return Quantity(self.instrument, self.size, self.path_id)

        max_trade_size = Decimal(options.max_trade_size)
        contained_size = max_trade_size / price
        contained_size = contained_size.quantize(Decimal(10)**-self.instrument.precision, rounding=ROUND_DOWN)
        return Quantity(self.instrument, contained_size, self.path_id) 
Example #6
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 #7
Source File: nodes.py    From vyper with Apache License 2.0 6 votes vote down vote up
def _op(self, left, right):
        # evaluate the operation using true division or floor division
        assert type(left) is type(right)
        if not right:
            raise ZeroDivisionException("Division by zero")

        if isinstance(left, decimal.Decimal):
            value = left / right
            if value < 0:
                # the EVM always truncates toward zero
                value = -(-left / right)
            # ensure that the result is truncated to MAX_DECIMAL_PLACES
            return value.quantize(
                decimal.Decimal(f"{1:0.{MAX_DECIMAL_PLACES}f}"), decimal.ROUND_DOWN
            )
        else:
            value = left // right
            if value < 0:
                return -(-left // right)
            return value 
Example #8
Source File: test_payment.py    From tbk with GNU General Public License v3.0 6 votes vote down vote up
def test_initialize_with_all_args(self):
        """
        Create Payment with all it's args
        """
        amount = Decimal(self.payment_kwargs['amount']).quantize(Decimal('.01'), rounding=ROUND_DOWN)
        payment = Payment(**self.payment_kwargs)
        self.assertEqual(payment.commerce, self.payment_kwargs['commerce'])
        self.assertEqual(payment.request_ip, self.payment_kwargs['request_ip'])
        self.assertEqual(payment.amount, amount)
        self.assertEqual(payment.order_id, self.payment_kwargs['order_id'])
        self.assertEqual(
            payment.success_url, self.payment_kwargs['success_url'])
        self.assertEqual(payment.confirmation_url, self.payment_kwargs['confirmation_url'])
        self.assertEqual(payment.session_id, self.payment_kwargs['session_id'])
        self.assertEqual(
            payment.failure_url, self.payment_kwargs['failure_url']) 
Example #9
Source File: gui_utils.py    From hashmal with GNU General Public License v3.0 5 votes vote down vote up
def set_satoshis(self, amount):
        if self.amount_format == 'satoshis':
            self.setText(str(amount))
        elif self.amount_format == 'coins':
            amount = Decimal(amount) / pow(10, 8)
            amount = amount.quantize(Decimal('0.00000001'), rounding=decimal.ROUND_DOWN)
            self.setText('{:f}'.format(amount)) 
Example #10
Source File: ch42.py    From matasano with GNU General Public License v3.0 5 votes vote down vote up
def cube_root(x):
    """Required because the usual x ^ 1/3 does not work with big integers."""
    decimal.getcontext().prec = 2 * len(str(x))
    power = decimal.Decimal(1) / decimal.Decimal(3)
    x = decimal.Decimal(str(x))
    root = x ** power

    integer_root = root.quantize(decimal.Decimal('1.'), rounding=decimal.ROUND_DOWN)
    return int(integer_root)

# Taken from Hal Finney's summary at https://www.ietf.org/mail-archive/web/openpgp/current/msg00999.html, 
Example #11
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 #12
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 #13
Source File: map_creator.py    From BORIS with GNU General Public License v3.0 5 votes vote down vote up
def intersection(A, B, C, D):
    """
    line segments intersection with decimal precision
    return True and coordinates of intersection point otherwise
    return False,None
    """
    getcontext().prec = 28

    Dec = decimal.Decimal
    xa, ya = Dec(str(A[0])), Dec(str(A[1]))
    xb, yb = Dec(str(B[0])), Dec(str(B[1]))
    xc, yc = Dec(str(C[0])), Dec(str(C[1]))
    xd, yd = Dec(str(D[0])), Dec(str(D[1]))

    # check if first segment is vertical
    if xa == xb:
        slope = (yc - yd) / (xc - xd)
        intersept = yc - slope * xc
        xm = xa
        ym = slope * xm + intersept

    # check if second segment is vertical
    elif xc == xd:
        slope = (ya - yb) / (xa - xb)
        intersept = ya - slope * xa
        xm = xc
        ym = slope * xm + intersept
    else:
        # round Decimal result: .quantize(Dec('.001'), rounding=decimal.ROUND_DOWN)
        xm = ((xd * xa * yc - xd * xb * yc - xd * xa * yb - xc * xa * yd + xc * xa * yb + xd * ya * xb + xc * xb * yd - xc * ya * xb) / (-yb * xd + yb * xc + ya * xd - ya * xc + xb * yd - xb * yc - xa * yd + xa * yc)).quantize(Dec('.001'), rounding=decimal.ROUND_DOWN)
        ym = ((yb * xc * yd - yb * yc * xd - ya * xc * yd + ya * yc * xd - xa * yb * yd + xa * yb * yc + ya * xb * yd - ya * xb * yc) / (-yb * xd + yb * xc + ya * xd - ya * xc + xb * yd - xb * yc - xa * yd + xa * yc)).quantize(Dec('.001'), rounding=decimal.ROUND_DOWN)

    xmin1, xmax1 = min(xa, xb), max(xa, xb)
    xmin2, xmax2 = min(xc, xd), max(xc, xd)
    ymin1, ymax1 = min(ya, yb), max(ya, yb)
    ymin2, ymax2 = min(yc, yd), max(yc, yd)

    return (xm >= xmin1 and xm <= xmax1 and xm >= xmin2 and xm <= xmax2 and ym >= ymin1 and ym <= ymax1 and ym >= ymin2 and ym <= ymax2) 
Example #14
Source File: payment_request_tools.py    From hypha with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def percentage(value, total):
    if not total:
        return decimal.Decimal(0)

    unrounded_total = (value / total) * 100

    # round using Decimal since we're dealing with currency
    rounded_total = unrounded_total.quantize(
        decimal.Decimal('0.0'),
        rounding=decimal.ROUND_DOWN,
    )

    return rounded_total 
Example #15
Source File: storage.py    From esdc-ce with Apache License 2.0 5 votes vote down vote up
def size_total(self):
        # We are working with decimal objects and rounding everything down
        decimal.getcontext().rounding = decimal.ROUND_DOWN
        return int(int(self.size) * float(self.size_coef)) 
Example #16
Source File: node.py    From esdc-ce with Apache License 2.0 5 votes vote down vote up
def cpu_total(self):
        decimal.getcontext().rounding = decimal.ROUND_DOWN
        return int(self.cpu * float(self.cpu_coef)) 
Example #17
Source File: node.py    From esdc-ce with Apache License 2.0 5 votes vote down vote up
def ram_total(self):
        decimal.getcontext().rounding = decimal.ROUND_DOWN
        return int(self.ram * float(self.ram_coef)) 
Example #18
Source File: node.py    From esdc-ce with Apache License 2.0 5 votes vote down vote up
def resources(self):
        """Return tuple with total (cpu, ram, disk) resources"""
        # We are working with decimal objects and rounding everything down
        decimal.getcontext().rounding = decimal.ROUND_DOWN

        # The total local disk size should not include backups and snapshots
        # TODO: fix ns.size_images and subtract it too
        disk_size_total = self.storage.size_total
        if self._ns:
            disk_size_total -= self._ns.size_backups + self._ns.size_snapshots + self._ns.size_rep_snapshots

        return self.cpu * float(self.cpu_coef), self.ram * float(self.ram_coef), disk_size_total 
Example #19
Source File: read.py    From stempeg with MIT License 5 votes vote down vote up
def float_to_str(f, precision=5):
    """
    Convert the given float to a string,
    without resorting to scientific notation
    """
    # create a new context for this task
    ctx = decimal.Context(rounding=decimal.ROUND_DOWN)

    # 12 digits should be enough to represent a single sample of
    # 192khz in float
    ctx.prec = precision

    d1 = ctx.create_decimal(repr(round(f, 5)))
    return format(d1, 'f') 
Example #20
Source File: models.py    From timestrap with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_total_cost(self):
        total_cost = Decimal()
        for entry in self.entries.iterator():
            try:
                if entry.task.hourly_rate:
                    total_cost += (
                        duration_decimal(entry.duration) * entry.task.hourly_rate
                    )
            except:  # noqa: E722
                continue
        return total_cost.quantize(Decimal(".01"), rounding=ROUND_DOWN) 
Example #21
Source File: util.py    From i-cant-believe-its-not-stake with MIT License 5 votes vote down vote up
def satoshi_round(amount):
    return Decimal(amount).quantize(Decimal('0.00000001'), rounding=ROUND_DOWN) 
Example #22
Source File: tx.py    From hashmal with GNU General Public License v3.0 5 votes vote down vote up
def format_amount(self, satoshis):
        if self.amount_format == 'satoshis':
            return str(satoshis)
        elif self.amount_format == 'coins':
            amount = Decimal(satoshis) / pow(10, 8)
            amount = amount.quantize(Decimal('0.00000001'), rounding=decimal.ROUND_DOWN)
            return '{:f}'.format(amount) 
Example #23
Source File: nodes.py    From vyper with Apache License 2.0 5 votes vote down vote up
def _op(self, left, right):
        assert type(left) is type(right)
        value = left * right
        if isinstance(left, decimal.Decimal):
            # ensure that the result is truncated to MAX_DECIMAL_PLACES
            return value.quantize(
                decimal.Decimal(f"{1:0.{MAX_DECIMAL_PLACES}f}"), decimal.ROUND_DOWN
            )
        else:
            return value 
Example #24
Source File: utils.py    From manila with Apache License 2.0 5 votes vote down vote up
def round_down(value, precision='0.00'):
    """Round a number downward using a specified level of precision.

    Example: round_down(float(total_space_in_bytes) / units.Gi, '0.01')
    """
    return float(decimal.Decimal(six.text_type(value)).quantize(
        decimal.Decimal(precision), rounding=decimal.ROUND_DOWN)) 
Example #25
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 #26
Source File: __init__.py    From minter-sdk with MIT License 5 votes vote down vote up
def to_bip(value):
        """
        Convert PIPs to BIPs.
        Use dynamic Decimal precision, depending on value length.
        Args:
            value (int|str|Decimal): value in PIP
        Returns:
            Decimal
        """
        # Check if value is correct PIP value
        value = str(value)
        if not value.isdigit():
            raise ValueError(f'{value} is not correct PIP value')

        # Get default decimal context
        context = decimal.getcontext()
        # Set temporary decimal context for calculation
        decimal.setcontext(
            decimal.Context(prec=len(value), rounding=decimal.ROUND_DOWN)
        )

        # Convert value
        value = decimal.Decimal(value) / decimal.Decimal(PIP)

        # Reset decimal context to default
        decimal.setcontext(context)

        return value 
Example #27
Source File: __init__.py    From minter-sdk with MIT License 5 votes vote down vote up
def convert_value(cls, value, to, prec=33):
        """
        Convert values from/to pip/bip.
        Args:
            value (string|int|Decimal|float): value to convert
            to (string): coin to convert value to
            prec (int): decimal context precision (decimal number length)
        Returns:
            int|Decimal
        """
        # Get default decimal context
        context = decimal.getcontext()
        # Set temporary decimal context for calculation
        decimal.setcontext(
            decimal.Context(prec=prec, rounding=decimal.ROUND_DOWN)
        )

        # PIP in BIP in Decimal
        default = decimal.Decimal(str(cls.DEFAULT))
        # Value in Decimal
        value = decimal.Decimal(str(value))

        # Make conversion
        if to == 'pip':
            value = int(value * default)
        elif to == 'bip':
            value /= default

        # Reset decimal context to default
        decimal.setcontext(context)

        return value 
Example #28
Source File: structure.py    From pyiron with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def f2qdec(self, f):
        return dec.Decimal(repr(f)).quantize(self.car_prec, dec.ROUND_DOWN) 
Example #29
Source File: TradeEngine.py    From cbpro-trader with GNU General Public License v3.0 5 votes vote down vote up
def round_coin(self, money):
        return Decimal(money).quantize(Decimal('.00000001'), rounding=ROUND_DOWN) 
Example #30
Source File: TradeEngine.py    From cbpro-trader with GNU General Public License v3.0 5 votes vote down vote up
def round_fiat(self, money):
        return Decimal(money).quantize(Decimal('.01'), rounding=ROUND_DOWN)