Python decimal.ROUND_FLOOR Examples

The following are 19 code examples of decimal.ROUND_FLOOR(). 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: utils.py    From pasportaservo with GNU Affero General Public License v3.0 6 votes vote down vote up
def bufferize_country_boundaries(country_code):
    if country_code not in COUNTRIES_GEO:
        return None
    buffer = (
        0 if country_code in COUNTRIES_WITH_NO_BUFFER
        else
        (0.01 if country_code in COUNTRIES_TINIEST else 0.1)
    )
    precision = decimal.Decimal('0.001')  # Three decimal places.
    bbox = {
        'northeast': [
            float(decimal.Decimal(c + buffer if c < +179.9 else c).quantize(precision, decimal.ROUND_CEILING))
            for c in COUNTRIES_GEO[country_code]['bbox']['northeast']
        ],
        'southwest': [
            float(decimal.Decimal(c - buffer if c > -179.9 else c).quantize(precision, decimal.ROUND_FLOOR))
            for c in COUNTRIES_GEO[country_code]['bbox']['southwest']
        ],
    }
    return {'bbox': bbox, 'center': COUNTRIES_GEO[country_code]['center']} 
Example #2
Source File: utils.py    From py-stellar-base with Apache License 2.0 6 votes vote down vote up
def best_rational_approximation(x):
    x = Decimal(x)
    int32_max = Decimal(2147483647)
    fractions = [[Decimal(0), Decimal(1)], [Decimal(1), Decimal(0)]]
    i = 2
    while True:
        if x > int32_max:
            break
        a = x.to_integral_exact(rounding=ROUND_FLOOR)
        f = x - a
        h = a * fractions[i - 1][0] + fractions[i - 2][0]
        k = a * fractions[i - 1][1] + fractions[i - 2][1]
        if h > int32_max or k > int32_max:
            break
        fractions.append([h, k])
        if f.is_zero():
            break
        x = 1 / f
        i = i + 1
    n = fractions[len(fractions) - 1][0]
    d = fractions[len(fractions) - 1][1]
    if n.is_zero() or d.is_zero():
        raise NoApproximationError("Couldn't find approximation.")
    return {"n": int(n), "d": int(d)} 
Example #3
Source File: xmp.py    From pdf-quench with GNU General Public License v2.0 6 votes vote down vote up
def _converter_date(value):
        m = iso8601.match(value)
        year = int(m.group("year"))
        month = int(m.group("month") or "1")
        day = int(m.group("day") or "1")
        hour = int(m.group("hour") or "0")
        minute = int(m.group("minute") or "0")
        second = decimal.Decimal(m.group("second") or "0")
        seconds = second.to_integral(decimal.ROUND_FLOOR)
        milliseconds = (second - seconds) * 1000000
        tzd = m.group("tzd") or "Z"
        dt = datetime.datetime(year, month, day, hour, minute, seconds, milliseconds)
        if tzd != "Z":
            tzd_hours, tzd_minutes = [int(x) for x in tzd.split(":")]
            tzd_hours *= -1
            if tzd_hours < 0:
                tzd_minutes *= -1
            dt = dt + datetime.timedelta(hours=tzd_hours, minutes=tzd_minutes)
        return dt 
Example #4
Source File: util.py    From planespotter with MIT License 5 votes vote down vote up
def round_decimal(value, prec):
    if isinstance(value, float):
        return round(value, prec)

    # can also use shift() here but that is 2.6 only
    return (value * decimal.Decimal("1" + "0" * prec)
            ).to_integral(decimal.ROUND_FLOOR) / \
        pow(10, prec) 
Example #5
Source File: util.py    From android_universal with MIT License 5 votes vote down vote up
def round_decimal(value, prec):
    if isinstance(value, float):
        return round(value, prec)

    # can also use shift() here but that is 2.6 only
    return (value * decimal.Decimal("1" + "0" * prec)
            ).to_integral(decimal.ROUND_FLOOR) / \
        pow(10, prec) 
Example #6
Source File: util.py    From moviegrabber with GNU General Public License v3.0 5 votes vote down vote up
def round_decimal(value, prec):
    if isinstance(value, float):
        return round(value, prec)

    # can also use shift() here but that is 2.6 only
    return (value * decimal.Decimal("1" + "0" * prec)
                    ).to_integral(decimal.ROUND_FLOOR) / \
                        pow(10, prec) 
Example #7
Source File: util.py    From jarvis with GNU General Public License v2.0 5 votes vote down vote up
def round_decimal(value, prec):
    if isinstance(value, float):
        return round(value, prec)

    # can also use shift() here but that is 2.6 only
    return (value * decimal.Decimal("1" + "0" * prec)
            ).to_integral(decimal.ROUND_FLOOR) / \
        pow(10, prec) 
Example #8
Source File: order_simulator.py    From btc_bot_framework with MIT License 5 votes vote down vote up
def bitflyer_fee_func(symbol, side, price, amount, fee_rate):
    ffb = 0  # fee from balance
    if symbol == 'BTC/JPY':
        f = Decimal(str(amount)) * Decimal(str(fee_rate))
        ffb = float(f.quantize(Decimal('0.00000001'), ROUND_FLOOR))
    info = {'commission': ffb, 'sfd': 0}
    return price * amount * fee_rate, ffb, info 
Example #9
Source File: util.py    From sqlalchemy with MIT License 5 votes vote down vote up
def round_decimal(value, prec):
    if isinstance(value, float):
        return round(value, prec)

    # can also use shift() here but that is 2.6 only
    return (value * decimal.Decimal("1" + "0" * prec)).to_integral(
        decimal.ROUND_FLOOR
    ) / pow(10, prec) 
Example #10
Source File: util.py    From stdm with GNU General Public License v2.0 5 votes vote down vote up
def round_decimal(value, prec):
    if isinstance(value, float):
        return round(value, prec)

    # can also use shift() here but that is 2.6 only
    return (value * decimal.Decimal("1" + "0" * prec)
            ).to_integral(decimal.ROUND_FLOOR) / \
        pow(10, prec) 
Example #11
Source File: util.py    From pyRevit with GNU General Public License v3.0 5 votes vote down vote up
def round_decimal(value, prec):
    if isinstance(value, float):
        return round(value, prec)

    # can also use shift() here but that is 2.6 only
    return (value * decimal.Decimal("1" + "0" * prec)
            ).to_integral(decimal.ROUND_FLOOR) / \
        pow(10, prec) 
Example #12
Source File: util.py    From jbox with MIT License 5 votes vote down vote up
def round_decimal(value, prec):
    if isinstance(value, float):
        return round(value, prec)

    # can also use shift() here but that is 2.6 only
    return (value * decimal.Decimal("1" + "0" * prec)
            ).to_integral(decimal.ROUND_FLOOR) / \
        pow(10, prec) 
Example #13
Source File: test_sqrt.py    From vyper with Apache License 2.0 5 votes vote down vote up
def decimal_truncate(val, decimal_places=DECIMAL_PLACES, rounding=ROUND_FLOOR):
    q = "0"
    if decimal_places != 0:
        q += "." + "0" * decimal_places

    return val.quantize(Decimal(q), rounding=rounding) 
Example #14
Source File: util.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def round_decimal(value, prec):
    if isinstance(value, float):
        return round(value, prec)

    # can also use shift() here but that is 2.6 only
    return (value * decimal.Decimal("1" + "0" * prec)
            ).to_integral(decimal.ROUND_FLOOR) / \
        pow(10, prec) 
Example #15
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 #16
Source File: utilities.py    From gprMax with GNU General Public License v3.0 5 votes vote down vote up
def round_value(value, decimalplaces=0):
    """Rounding function.

    Args:
        value (float): Number to round.
        decimalplaces (int): Number of decimal places of float to represent rounded value.

    Returns:
        rounded (int/float): Rounded value.
    """

    # Rounds to nearest integer (half values are rounded downwards)
    if decimalplaces == 0:
        rounded = int(d.Decimal(value).quantize(d.Decimal('1'), rounding=d.ROUND_HALF_DOWN))

    # Rounds down to nearest float represented by number of decimal places
    else:
        precision = '1.{places}'.format(places='0' * decimalplaces)
        rounded = float(d.Decimal(value).quantize(d.Decimal(precision), rounding=d.ROUND_FLOOR))

    return rounded 
Example #17
Source File: fuel.py    From biweeklybudget with GNU Affero General Public License v3.0 5 votes vote down vote up
def calculate_mpg(self):
        """
        Calculate ``calculated_mpg`` field.

        :returns: True if recalculate, False if unable to calculate
        :rtype: bool
        """
        if self.gallons is None:
            logger.warning(
                'Gallons is none; cannot recalculate MPG for %s', self
            )
            return False
        if self.odometer_miles is None:
            logger.warning(
                'odometer_miles is none; cannot recalculate MPG for %s', self
            )
            return False
        prev = self._previous_entry()
        if prev is None:
            logger.warning('Previous entry is None; cannot recalculate MPG '
                           'for %s', self)
            return False
        distance = self.odometer_miles - prev.odometer_miles
        self.calculated_miles = distance
        self.calculated_mpg = (
            (distance * Decimal(1.0)) / self.gallons
        ).quantize(Decimal('.001'), rounding=ROUND_FLOOR)
        logger.debug('Calculate MPG for fill %d: distance=%s mpg=%s',
                     self.id, distance, self.calculated_mpg)
        inspect(self).session.add(self) 
Example #18
Source File: gacha.py    From yui with GNU Affero General Public License v3.0 5 votes vote down vote up
def to_percent(v: Decimal, q=CHANCE_MIN) -> str:
    s = str((v * 100).quantize(q, rounding=ROUND_FLOOR))
    if '.' in s:
        return s.rstrip('0').rstrip('.')
    return s 
Example #19
Source File: SpinBox.py    From tf-pose with Apache License 2.0 5 votes vote down vote up
def stepBy(self, n):
        n = D(int(n))   ## n must be integral number of steps.
        s = [D(-1), D(1)][n >= 0]  ## determine sign of step
        val = self.val
        
        for i in range(int(abs(n))):
            
            if self.opts['log']:
                raise Exception("Log mode no longer supported.")
            #    step = abs(val) * self.opts['step']
            #    if 'minStep' in self.opts:
            #        step = max(step, self.opts['minStep'])
            #    val += step * s
            if self.opts['dec']:
                if val == 0:
                    step = self.opts['minStep']
                    exp = None
                else:
                    vs = [D(-1), D(1)][val >= 0]
                    #exp = D(int(abs(val*(D('1.01')**(s*vs))).log10()))
                    fudge = D('1.01')**(s*vs) ## fudge factor. at some places, the step size depends on the step sign.
                    exp = abs(val * fudge).log10().quantize(1, decimal.ROUND_FLOOR)
                    step = self.opts['step'] * D(10)**exp
                if 'minStep' in self.opts:
                    step = max(step, self.opts['minStep'])
                val += s * step
                #print "Exp:", exp, "step", step, "val", val
            else:
                val += s*self.opts['step']
                
            if 'minStep' in self.opts and abs(val) < self.opts['minStep']:
                val = D(0)
        self.setValue(val, delaySignal=True)  ## note all steps (arrow buttons, wheel, up/down keys..) emit delayed signals only.