Python decimal.ROUND_HALF_UP Examples
The following are 30
code examples of decimal.ROUND_HALF_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: utils.py From pdfplumber with MIT License | 6 votes |
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))
Example #2
Source File: price.py From betfair.py with MIT License | 6 votes |
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)
Example #3
Source File: excellib.py From koala with GNU General Public License v3.0 | 6 votes |
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)
Example #4
Source File: account_move.py From LibrERP with GNU Affero General Public License v3.0 | 6 votes |
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
Example #5
Source File: misc.py From clusterman with Apache License 2.0 | 6 votes |
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
Example #6
Source File: sigproc_orig.py From python_kaldi_features with MIT License | 5 votes |
def round_half_up(number): return int(decimal.Decimal(number).quantize(decimal.Decimal('1'), rounding=decimal.ROUND_HALF_UP))
Example #7
Source File: common.py From integrations-core with BSD 3-Clause "New" or "Revised" License | 5 votes |
def round_value(value, precision=0, rounding_method=ROUND_HALF_UP): precision = '0.{}'.format('0' * precision) return float(Decimal(str(value)).quantize(Decimal(precision), rounding=rounding_method))
Example #8
Source File: models.py From openprocurement.api with Apache License 2.0 | 5 votes |
def _apply_precision(self, value): try: value = Decimal(value).quantize(self.precision, rounding=ROUND_HALF_UP).normalize() except (TypeError, InvalidOperation): raise ConversionError(self.messages['number_coerce'].format(value)) return value
Example #9
Source File: _compat.py From script.elementum.burst with Do What The F*ck You Want To Public License | 5 votes |
def round_py2_compat(what): """ Python 2 and Python 3 use different rounding strategies in round(). This function ensures that results are python2/3 compatible and backward compatible with previous py2 releases :param what: float :return: rounded long """ d = Context( prec=len(str(long(what))), # round to integer with max precision rounding=decimal.ROUND_HALF_UP ).create_decimal(str(what)) # str(): python 2.6 compat return long(d)
Example #10
Source File: helpers.py From neutron-lib with Apache License 2.0 | 5 votes |
def round_val(val): """Round the value. :param val: The value to round. :returns: The value rounded using the half round up scheme. """ # we rely on decimal module since it behaves consistently across Python # versions (2.x vs. 3.x) return int(decimal.Decimal(val).quantize(decimal.Decimal('1'), rounding=decimal.ROUND_HALF_UP))
Example #11
Source File: rds.py From cloud-custodian with Apache License 2.0 | 5 votes |
def process(self, resources): c = local_session(self.manager.session_factory).client('rds') for r in resources: old_val = D(r['AllocatedStorage']) _100 = D(100) new_val = ((_100 + D(self.data['percent'])) / _100) * old_val rounded = int(new_val.quantize(D('0'), ROUND_HALF_UP)) c.modify_db_instance( DBInstanceIdentifier=r['DBInstanceIdentifier'], AllocatedStorage=rounded, ApplyImmediately=self.data.get('immediate', False))
Example #12
Source File: format_util.py From betterlifepsi with MIT License | 5 votes |
def format_decimal(value): """ Format a decimal with two decimal point with rounding mode ROUND_HALF_UP :param value the decimal to format """ return Decimal( Decimal(value).quantize(Decimal('.01'), rounding=ROUND_HALF_UP))
Example #13
Source File: st_color_scheme_matcher.py From sublime-markdown-popups with MIT License | 5 votes |
def fmt_float(f, p=0): """Set float precision and trim precision zeros.""" string = str( decimal.Decimal(f).quantize(decimal.Decimal('0.' + ('0' * p) if p > 0 else '0'), decimal.ROUND_HALF_UP) ) m = FLOAT_TRIM_RE.match(string) if m: string = m.group('keep') if m.group('keep2'): string += m.group('keep2') return string
Example #14
Source File: models.py From longclaw_demo with MIT License | 5 votes |
def price(self): if self.discount: discount_price = self.base_price * decimal.Decimal((100 - self.discount_percent) / 100.0 ) return discount_price.quantize(decimal.Decimal('.01'), decimal.ROUND_HALF_UP) return self.base_price
Example #15
Source File: _compat.py From bazarr with GNU General Public License v3.0 | 5 votes |
def round_py2_compat(what): """ Python 2 and Python 3 use different rounding strategies in round(). This function ensures that results are python2/3 compatible and backward compatible with previous py2 releases :param what: float :return: rounded long """ d = Context( prec=len(str(long(what))), # round to integer with max precision rounding=decimal.ROUND_HALF_UP ).create_decimal(str(what)) # str(): python 2.6 compat return long(d)
Example #16
Source File: sigproc.py From python_kaldi_features with MIT License | 5 votes |
def round_half_up(number): return int(decimal.Decimal(number).quantize(decimal.Decimal('1'), rounding=decimal.ROUND_HALF_UP))
Example #17
Source File: color_helper_util.py From ColorHelper with MIT License | 5 votes |
def fmt_float(f, p=0): """Set float precision and trim precision zeros.""" string = str( decimal.Decimal(f).quantize(decimal.Decimal('0.' + ('0' * p) if p > 0 else '0'), decimal.ROUND_HALF_UP) ) m = FLOAT_TRIM_RE.match(string) if m: string = m.group('keep') if m.group('keep2'): string += m.group('keep2') return string
Example #18
Source File: sigproc.py From delta with Apache License 2.0 | 5 votes |
def round_half_up(number): ''' To nearest with ties going away from zero. ''' return int( decimal.Decimal(number).quantize( decimal.Decimal('1'), rounding=decimal.ROUND_HALF_UP))
Example #19
Source File: audio_utils.py From asr-study with MIT License | 5 votes |
def round_half_up(number): return int(decimal.Decimal(number).quantize(decimal.Decimal('1'), rounding=decimal.ROUND_HALF_UP ))
Example #20
Source File: _compat.py From elasticintel with GNU General Public License v3.0 | 5 votes |
def round_py2_compat(what): """ Python 2 and Python 3 use different rounding strategies in round(). This function ensures that results are python2/3 compatible and backward compatible with previous py2 releases :param what: float :return: rounded long """ d = Context( prec=len(str(long(what))), # round to integer with max precision rounding=decimal.ROUND_HALF_UP ).create_decimal(str(what)) # str(): python 2.6 compat return long(d)
Example #21
Source File: processing.py From speechpy with Apache License 2.0 | 5 votes |
def round_half_up(number): return int( decimal.Decimal(number).quantize( decimal.Decimal('1'), rounding=decimal.ROUND_HALF_UP))
Example #22
Source File: st_scheme_template.py From sublime-markdown-popups with MIT License | 5 votes |
def fmt_float(f, p=0): """Set float precision and trim precision zeros.""" string = str( decimal.Decimal(f).quantize(decimal.Decimal('0.' + ('0' * p) if p > 0 else '0'), decimal.ROUND_HALF_UP) ) m = re_float_trim.match(string) if m: string = m.group('keep') if m.group('keep2'): string += m.group('keep2') return string
Example #23
Source File: BeamOperations.py From ray_scripts with GNU General Public License v3.0 | 5 votes |
def mu_rounded(beam): """ Compute the monitor units for the raystation beam to the nearest MU using the Round_Half_Up strategy :param beam: :return: a rounded float of the beam MU """ from decimal import Decimal, ROUND_HALF_UP init_mu = beam.BeamMU dec_mu = Decimal(init_mu).quantize(Decimal('0.1'), rounding=ROUND_HALF_UP) return float(dec_mu)
Example #24
Source File: make_screenshots.py From biweeklybudget with GNU Affero General Public License v3.0 | 5 votes |
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()
Example #25
Source File: cli.py From pdfplumber with MIT License | 5 votes |
def default(self, o): if isinstance(o, Decimal): return float(o.quantize(Decimal('.0001'), rounding=ROUND_HALF_UP)) return super(DecimalEncoder, self).default(o)
Example #26
Source File: __init__.py From hammer with BSD 3-Clause "New" or "Revised" License | 5 votes |
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
Example #27
Source File: math.py From formulas with European Union Public License 1.1 | 5 votes |
def round_up(x): return float(Decimal(x).quantize(0, rounding=ROUND_HALF_UP))
Example #28
Source File: test_ocp_azure_query_handler.py From koku with GNU Affero General Public License v3.0 | 5 votes |
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) )
Example #29
Source File: tests_azure_query_handler.py From koku with GNU Affero General Public License v3.0 | 5 votes |
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) )
Example #30
Source File: data_types.py From hutils with MIT License | 5 votes |
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)