Python decimal.ROUND_HALF_EVEN() Examples

The following are code examples for showing how to use decimal.ROUND_HALF_EVEN(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: vscode-mayapy   Author: FXTD-ODYSSEY   File: pie_slice.py    MIT License 6 votes vote down vote up
def round(number, ndigits=None):
        return_int = False
        if ndigits is None:
            return_int = True
            ndigits = 0
        if hasattr(number, '__round__'):
            return number.__round__(ndigits)

        if ndigits < 0:
            raise NotImplementedError('negative ndigits not supported yet')
        exponent = Decimal('10') ** (-ndigits)
        d = Decimal.from_float(number).quantize(exponent,
                                                rounding=ROUND_HALF_EVEN)
        if return_int:
            return int(d)
        else:
            return float(d) 
Example 2
Project: GADM_DBSCAN   Author: JimHaughwout   File: utils.py    MIT License 6 votes vote down vote up
def half_even(num_val, n_places=s.DEFAULT_ROUNDING):
    """
    ROUND_HALF_EVEN a point to n_places decimal places
    """
    if not 0 < n_places <= 8:
        print "Can only round to 1-8 decimal places. Rounding to default"
        n_places = s.DEFAULT_ROUNDING

    try:
        rounding = str(10**int(-1 * n_places))
        x = float(decimal.Decimal("%s" % num_val).quantize(decimal.Decimal(rounding), 
            rounding=decimal.ROUND_HALF_EVEN))
    except ValueError as e:
        e = "Could not round %r" % num_val
        print e
        raise
    return x 
Example 3
Project: LFA   Author: L-Andrade   File: RegistryParse.py    GNU General Public License v3.0 6 votes vote down vote up
def parse_timestamp(ticks, resolution, epoch, mode=decimal.ROUND_HALF_EVEN):
    """
    Generalized function for parsing timestamps

    :param ticks: number of time units since the epoch
    :param resolution: number of time units per second
    :param epoch: the datetime of this timestamp's epoch
    :param mode: decimal rounding mode
    :return: datetime.datetime
    """
    # python's datetime.datetime supports microsecond precision
    datetime_resolution = int(1e6)

    # convert ticks since epoch to microseconds since epoch
    us = int((decimal.Decimal(ticks * datetime_resolution) / decimal.Decimal(resolution)).quantize(1, mode))

    # convert to datetime
    return epoch + datetime.timedelta(microseconds=us) 
Example 4
Project: plistutils   Author: strozfriedberg   File: utils.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def parse_timestamp(qword, resolution, epoch_shift, mode=decimal.ROUND_HALF_EVEN):
    """
    Generalized function for parsing timestamps

    :param qword: number of time units since the epoch
    :param resolution: number of time units per second
    :param epoch_shift: difference in seconds between UNIX epoch (1970-1-1)
                        and epoch of qword
    :param mode: decimal rounding mode
    :return: datetime.datetime
    """
    # convert qword from given epoch to UNIX epoch
    shifted = qword - epoch_shift * resolution
    # python's datetime.datetime supports microsecond precision
    datetime_resolution = int(1e6)

    # total number of microseconds since UNIX epoch
    # python 3 round() returns int, python 2 round() returns float
    total_microseconds = (decimal.Decimal(shifted * datetime_resolution) / decimal.Decimal(resolution)).quantize(1, mode)

    # convert to datetime
    return datetime.utcfromtimestamp(total_microseconds // datetime_resolution).replace(microsecond=total_microseconds % datetime_resolution) 
Example 5
Project: AsemanOs   Author: AsemanOS   File: pie_slice.py    GNU General Public License v3.0 6 votes vote down vote up
def round(number, ndigits=None):
        return_int = False
        if ndigits is None:
            return_int = True
            ndigits = 0
        if hasattr(number, '__round__'):
            return number.__round__(ndigits)

        if ndigits < 0:
            raise NotImplementedError('negative ndigits not supported yet')
        exponent = Decimal('10') ** (-ndigits)
        d = Decimal.from_float(number).quantize(exponent,
                                                rounding=ROUND_HALF_EVEN)
        if return_int:
            return int(d)
        else:
            return float(d) 
Example 6
Project: JukeBox   Author: gauravsarkar97   File: _util.py    MIT License 5 votes vote down vote up
def intround(value):
    """Given a float returns a rounded int. Should give the same result on
    both Py2/3
    """

    return int(decimal.Decimal.from_float(
        value).to_integral_value(decimal.ROUND_HALF_EVEN)) 
Example 7
Project: bugatsinho.github.io   Author: bugatsinho   File: _util.py    GNU General Public License v3.0 5 votes vote down vote up
def intround(value):
    """Given a float returns a rounded int. Should give the same result on
    both Py2/3
    """

    return int(decimal.Decimal.from_float(
        value).to_integral_value(decimal.ROUND_HALF_EVEN)) 
Example 8
Project: messenger-emulator   Author: sDextra   File: _util.py    MIT License 5 votes vote down vote up
def intround(value):
    """Given a float returns a rounded int. Should give the same result on
    both Py2/3
    """

    return int(decimal.Decimal.from_float(
        value).to_integral_value(decimal.ROUND_HALF_EVEN)) 
Example 9
Project: noobotkit   Author: nazroll   File: fields.py    MIT License 5 votes vote down vote up
def format(self, value):
        dvalue = MyDecimal(value)
        if not dvalue.is_normal() and dvalue != ZERO:
            raise MarshallingException('Invalid Fixed precision number.')
        return six.text_type(dvalue.quantize(self.precision, rounding=ROUND_HALF_EVEN)) 
Example 10
Project: xuemc   Author: skycucumber   File: fields.py    GNU General Public License v2.0 5 votes vote down vote up
def format(self, value):
        dvalue = MyDecimal(value)
        if not dvalue.is_normal() and dvalue != ZERO:
            raise MarshallingException('Invalid Fixed precision number.')
        return six.text_type(dvalue.quantize(self.precision, rounding=ROUND_HALF_EVEN)) 
Example 11
Project: pyiron   Author: pyiron   File: structure.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def f2s(self, f):
        return str(dec.Decimal(repr(f)).quantize(self.car_prec, dec.ROUND_HALF_EVEN)) 
Example 12
Project: url_shortener   Author: martydill   File: fields.py    MIT License 5 votes vote down vote up
def format(self, value):
        dvalue = MyDecimal(value)
        if not dvalue.is_normal() and dvalue != ZERO:
            raise MarshallingException('Invalid Fixed precision number.')
        return six.text_type(dvalue.quantize(self.precision, rounding=ROUND_HALF_EVEN)) 
Example 13
Project: claripy   Author: angr   File: fp.py    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 14
Project: go2mapillary   Author: enricofer   File: encoder.py    GNU General Public License v3.0 5 votes vote down vote up
def _round_quantize(self, val):

        # round() has different behavior in python 2/3
        # For consistency between 2 and 3 we use quantize, however
        # it is slower than the built in round function.
        d = decimal.Decimal(val)
        rounded = d.quantize(1, rounding=decimal.ROUND_HALF_EVEN)
        return float(rounded) 
Example 15
Project: pipa-pay-server   Author: davidvon   File: fields.py    Apache License 2.0 5 votes vote down vote up
def format(self, value):
        dvalue = MyDecimal(value)
        if not dvalue.is_normal() and dvalue != ZERO:
            raise MarshallingException('Invalid Fixed precision number.')
        return six.text_type(dvalue.quantize(self.precision, rounding=ROUND_HALF_EVEN)) 
Example 16
Project: junior_project   Author: tishq   File: fields.py    MIT License 5 votes vote down vote up
def format(self, value):
        dvalue = MyDecimal(value)
        if not dvalue.is_normal() and dvalue != ZERO:
            raise MarshallingException('Invalid Fixed precision number.')
        return six.text_type(dvalue.quantize(self.precision, rounding=ROUND_HALF_EVEN)) 
Example 17
Project: junior_project   Author: tishq   File: fields.py    MIT License 5 votes vote down vote up
def format(self, value):
        dvalue = MyDecimal(value)
        if not dvalue.is_normal() and dvalue != ZERO:
            raise MarshallingException('Invalid Fixed precision number.')
        return six.text_type(dvalue.quantize(self.precision, rounding=ROUND_HALF_EVEN)) 
Example 18
Project: core-python   Author: part-os   File: common.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def dollars(self):
        return Decimal(
            self.raw_amount.quantize(ROUND_TO, rounding=decimal.ROUND_HALF_EVEN)
        ) 
Example 19
Project: health-mosconi   Author: GNUHealth-Mosconi   File: currency.py    GNU General Public License v3.0 5 votes vote down vote up
def round(self, amount, rounding=ROUND_HALF_EVEN):
        'Round the amount depending of the currency'
        return (amount / self.rounding).quantize(Decimal('1.'),
                rounding=rounding) * self.rounding 
Example 20
Project: sec-edgar-tools   Author: altova   File: efm_validation.py    Apache License 2.0 5 votes vote down vote up
def decimal_comparison(fact1, fact2, cmp):
    """Rounds both numerical facts to the least accurate precision of both facts and calls the given cmp function with the rounded decimal values."""
    decimals = min(fact1.decimals, fact2.decimals)
    if decimals == float('inf'):
        return cmp(fact1.numeric_value, fact2.numeric_value)
    val1 = fact1.numeric_value.scaleb(decimals).quantize(1, decimal.ROUND_HALF_EVEN).scaleb(-decimals)
    val2 = fact2.numeric_value.scaleb(decimals).quantize(1, decimal.ROUND_HALF_EVEN).scaleb(-decimals)
    return cmp(val1, val2, decimals) 
Example 21
Project: coinpark   Author: discountry   File: bot.py    MIT License 5 votes vote down vote up
def handler():
    ticker = coinpark.get_pair_ticker(pair)
    buy = ticker['buy']
    print('buy_price', buy)
    sell = ticker['sell']
    print('sell_price', sell)
    margin = buy - sell

    if margin > 0:
        coinpark.batch_limit_buy_sell(pair, Decimal((buy + sell) / 2).quantize(Decimal(price_precision), rounding=ROUND_HALF_EVEN), amount) 
Example 22
Project: Repobot   Author: Desgard   File: newround.py    MIT License 4 votes vote down vote up
def newround(number, ndigits=None):
    """
    See Python 3 documentation: uses Banker's Rounding.
 
    Delegates to the __round__ method if for some reason this exists.
 
    If not, rounds a number to a given precision in decimal digits (default
    0 digits). This returns an int when called with one argument,
    otherwise the same type as the number. ndigits may be negative.
 
    See the test_round method in future/tests/test_builtins.py for
    examples.
    """
    return_int = False
    if ndigits is None:
        return_int = True
        ndigits = 0
    if hasattr(number, '__round__'):
        return number.__round__(ndigits)
    
    if ndigits < 0:
        raise NotImplementedError('negative ndigits not supported yet')
    exponent = Decimal('10') ** (-ndigits)

    if PYPY:
        # Work around issue #24: round() breaks on PyPy with NumPy's types
        if 'numpy' in repr(type(number)):
            number = float(number)

    if not PY26:
        d = Decimal.from_float(number).quantize(exponent,
                                            rounding=ROUND_HALF_EVEN)
    else:
        d = from_float_26(number).quantize(exponent, rounding=ROUND_HALF_EVEN)

    if return_int:
        return int(d)
    else:
        return float(d)
 

### From Python 2.7's decimal.py. Only needed to support Py2.6: 
Example 23
Project: otRebuilder   Author: Pal3love   File: py23.py    MIT License 4 votes vote down vote up
def round3(number, ndigits=None):
		"""
		Implementation of Python 3 built-in round() function.

		Rounds a number to a given precision in decimal digits (default
		0 digits). This returns an int when ndigits is omitted or is None,
		otherwise the same type as the number.

		Values are rounded to the closest multiple of 10 to the power minus
		ndigits; if two multiples are equally close, rounding is done toward
		the even choice (aka "Banker's Rounding"). For example, both round(0.5)
		and round(-0.5) are 0, and round(1.5) is 2.

		ndigits may be negative.

		See Python 3 documentation:
		https://docs.python.org/3/library/functions.html?highlight=round#round

		Derived from python-future:
		https://github.com/PythonCharmers/python-future/blob/master/src/future/builtins/newround.py
		"""
		if ndigits is None:
			ndigits = 0
			# return an int when called with one argument
			totype = int
			# shortcut if already an integer, or a float with no decimal digits
			inumber = totype(number)
			if inumber == number:
				return inumber
		else:
			# return the same type as the number, when called with two arguments
			totype = type(number)

		m = number * (10 ** ndigits)
		# if number is half-way between two multiples, and the mutliple that is
		# closer to zero is even, we use the (slow) pure-Python implementation
		if isclose(m % 1, .5) and int(m) % 2 == 0:
			if ndigits < 0:
				exponent = 10 ** (-ndigits)
				quotient, remainder = divmod(number, exponent)
				half = exponent//2
				if remainder > half or (remainder == half and quotient % 2 != 0):
					quotient += 1
				d = quotient * exponent
			else:
				exponent = _decimal.Decimal('10') ** (-ndigits) if ndigits != 0 else 1

				d = _decimal.Decimal.from_float(number).quantize(
					exponent, rounding=_decimal.ROUND_HALF_EVEN)
		else:
			# else we use the built-in round() as it produces the same results
			d = round2(number, ndigits)

		return totype(d) 
Example 24
Project: FightstickDisplay   Author: calexil   File: newround.py    GNU General Public License v3.0 4 votes vote down vote up
def newround(number, ndigits=None):
    """
    See Python 3 documentation: uses Banker's Rounding.
 
    Delegates to the __round__ method if for some reason this exists.
 
    If not, rounds a number to a given precision in decimal digits (default
    0 digits). This returns an int when called with one argument,
    otherwise the same type as the number. ndigits may be negative.
 
    See the test_round method in future/tests/test_builtins.py for
    examples.
    """
    return_int = False
    if ndigits is None:
        return_int = True
        ndigits = 0
    if hasattr(number, '__round__'):
        return number.__round__(ndigits)
    
    if ndigits < 0:
        raise NotImplementedError('negative ndigits not supported yet')
    exponent = Decimal('10') ** (-ndigits)

    if PYPY:
        # Work around issue #24: round() breaks on PyPy with NumPy's types
        if 'numpy' in repr(type(number)):
            number = float(number)

    if not PY26:
        d = Decimal.from_float(number).quantize(exponent,
                                            rounding=ROUND_HALF_EVEN)
    else:
        d = from_float_26(number).quantize(exponent, rounding=ROUND_HALF_EVEN)

    if return_int:
        return int(d)
    else:
        return float(d)
 

### From Python 2.7's decimal.py. Only needed to support Py2.6: 
Example 25
Project: hackathon   Author: vertica   File: newround.py    Apache License 2.0 4 votes vote down vote up
def newround(number, ndigits=None):
    """
    See Python 3 documentation: uses Banker's Rounding.
 
    Delegates to the __round__ method if for some reason this exists.
 
    If not, rounds a number to a given precision in decimal digits (default
    0 digits). This returns an int when called with one argument,
    otherwise the same type as the number. ndigits may be negative.
 
    See the test_round method in future/tests/test_builtins.py for
    examples.
    """
    return_int = False
    if ndigits is None:
        return_int = True
        ndigits = 0
    if hasattr(number, '__round__'):
        return number.__round__(ndigits)
    
    if ndigits < 0:
        raise NotImplementedError('negative ndigits not supported yet')
    exponent = Decimal('10') ** (-ndigits)

    if PYPY:
        # Work around issue #24: round() breaks on PyPy with NumPy's types
        if 'numpy' in repr(type(number)):
            number = float(number)

    if not PY26:
        d = Decimal.from_float(number).quantize(exponent,
                                            rounding=ROUND_HALF_EVEN)
    else:
        d = from_float_26(number).quantize(exponent, rounding=ROUND_HALF_EVEN)

    if return_int:
        return int(d)
    else:
        return float(d)
 

### From Python 2.7's decimal.py. Only needed to support Py2.6: 
Example 26
Project: TFTHelper   Author: AliMZaini   File: newround.py    MIT License 4 votes vote down vote up
def newround(number, ndigits=None):
    """
    See Python 3 documentation: uses Banker's Rounding.

    Delegates to the __round__ method if for some reason this exists.

    If not, rounds a number to a given precision in decimal digits (default
    0 digits). This returns an int when called with one argument,
    otherwise the same type as the number. ndigits may be negative.

    See the test_round method in future/tests/test_builtins.py for
    examples.
    """
    return_int = False
    if ndigits is None:
        return_int = True
        ndigits = 0
    if hasattr(number, '__round__'):
        return number.__round__(ndigits)

    if ndigits < 0:
        raise NotImplementedError('negative ndigits not supported yet')
    exponent = Decimal('10') ** (-ndigits)

    if PYPY:
        # Work around issue #24: round() breaks on PyPy with NumPy's types
        if 'numpy' in repr(type(number)):
            number = float(number)

    if not PY26:
        d = Decimal.from_float(number).quantize(exponent,
                                            rounding=ROUND_HALF_EVEN)
    else:
        d = from_float_26(number).quantize(exponent, rounding=ROUND_HALF_EVEN)

    if return_int:
        return int(d)
    else:
        return float(d)


### From Python 2.7's decimal.py. Only needed to support Py2.6: 
Example 27
Project: kgsgo-dataset-preprocessor   Author: hughperkins   File: newround.py    Mozilla Public License 2.0 4 votes vote down vote up
def newround(number, ndigits=None):
    """
    See Python 3 documentation: uses Banker's Rounding.
 
    Delegates to the __round__ method if for some reason this exists.
 
    If not, rounds a number to a given precision in decimal digits (default
    0 digits). This returns an int when called with one argument,
    otherwise the same type as the number. ndigits may be negative.
 
    See the test_round method in future/tests/test_builtins.py for
    examples.
    """
    return_int = False
    if ndigits is None:
        return_int = True
        ndigits = 0
    if hasattr(number, '__round__'):
        return number.__round__(ndigits)
    
    if ndigits < 0:
        raise NotImplementedError('negative ndigits not supported yet')
    exponent = Decimal('10') ** (-ndigits)

    if PYPY:
        # Work around issue #24: round() breaks on PyPy with NumPy's types
        if 'numpy' in repr(type(number)):
            number = float(number)

    if not PY26:
        d = Decimal.from_float(number).quantize(exponent,
                                            rounding=ROUND_HALF_EVEN)
    else:
        d = from_float_26(number).quantize(exponent, rounding=ROUND_HALF_EVEN)

    if return_int:
        return int(d)
    else:
        return float(d)
 

### From Python 2.7's decimal.py. Only needed to support Py2.6: 
Example 28
Project: packaging   Author: blockstack   File: newround.py    GNU General Public License v3.0 4 votes vote down vote up
def newround(number, ndigits=None):
    """
    See Python 3 documentation: uses Banker's Rounding.
 
    Delegates to the __round__ method if for some reason this exists.
 
    If not, rounds a number to a given precision in decimal digits (default
    0 digits). This returns an int when called with one argument,
    otherwise the same type as the number. ndigits may be negative.
 
    See the test_round method in future/tests/test_builtins.py for
    examples.
    """
    return_int = False
    if ndigits is None:
        return_int = True
        ndigits = 0
    if hasattr(number, '__round__'):
        return number.__round__(ndigits)
    
    if ndigits < 0:
        raise NotImplementedError('negative ndigits not supported yet')
    exponent = Decimal('10') ** (-ndigits)

    if PYPY:
        # Work around issue #24: round() breaks on PyPy with NumPy's types
        if 'numpy' in repr(type(number)):
            number = float(number)

    if not PY26:
        d = Decimal.from_float(number).quantize(exponent,
                                            rounding=ROUND_HALF_EVEN)
    else:
        d = from_float_26(number).quantize(exponent, rounding=ROUND_HALF_EVEN)

    if return_int:
        return int(d)
    else:
        return float(d)
 

### From Python 2.7's decimal.py. Only needed to support Py2.6: 
Example 29
Project: geofire-python   Author: ininex   File: newround.py    MIT License 4 votes vote down vote up
def newround(number, ndigits=None):
    """
    See Python 3 documentation: uses Banker's Rounding.
 
    Delegates to the __round__ method if for some reason this exists.
 
    If not, rounds a number to a given precision in decimal digits (default
    0 digits). This returns an int when called with one argument,
    otherwise the same type as the number. ndigits may be negative.
 
    See the test_round method in future/tests/test_builtins.py for
    examples.
    """
    return_int = False
    if ndigits is None:
        return_int = True
        ndigits = 0
    if hasattr(number, '__round__'):
        return number.__round__(ndigits)
    
    if ndigits < 0:
        raise NotImplementedError('negative ndigits not supported yet')
    exponent = Decimal('10') ** (-ndigits)

    if PYPY:
        # Work around issue #24: round() breaks on PyPy with NumPy's types
        if 'numpy' in repr(type(number)):
            number = float(number)

    if not PY26:
        d = Decimal.from_float(number).quantize(exponent,
                                            rounding=ROUND_HALF_EVEN)
    else:
        d = from_float_26(number).quantize(exponent, rounding=ROUND_HALF_EVEN)

    if return_int:
        return int(d)
    else:
        return float(d)
 

### From Python 2.7's decimal.py. Only needed to support Py2.6: 
Example 30
Project: PoliNetworkBotPython   Author: PoliNetwork   File: newround.py    MIT License 4 votes vote down vote up
def newround(number, ndigits=None):
    """
    See Python 3 documentation: uses Banker's Rounding.

    Delegates to the __round__ method if for some reason this exists.

    If not, rounds a number to a given precision in decimal digits (default
    0 digits). This returns an int when called with one argument,
    otherwise the same type as the number. ndigits may be negative.

    See the test_round method in future/tests/test_builtins.py for
    examples.
    """
    return_int = False
    if ndigits is None:
        return_int = True
        ndigits = 0
    if hasattr(number, '__round__'):
        return number.__round__(ndigits)

    if ndigits < 0:
        raise NotImplementedError('negative ndigits not supported yet')
    exponent = Decimal('10') ** (-ndigits)

    if PYPY:
        # Work around issue #24: round() breaks on PyPy with NumPy's types
        if 'numpy' in repr(type(number)):
            number = float(number)

    if isinstance(number, Decimal):
        d = number
    else:
        if not PY26:
            d = Decimal.from_float(number).quantize(exponent,
                                                rounding=ROUND_HALF_EVEN)
        else:
            d = from_float_26(number).quantize(exponent, rounding=ROUND_HALF_EVEN)

    if return_int:
        return int(d)
    else:
        return float(d)


### From Python 2.7's decimal.py. Only needed to support Py2.6: 
Example 31
Project: islam-buddy   Author: hamir   File: newround.py    MIT License 4 votes vote down vote up
def newround(number, ndigits=None):
    """
    See Python 3 documentation: uses Banker's Rounding.
 
    Delegates to the __round__ method if for some reason this exists.
 
    If not, rounds a number to a given precision in decimal digits (default
    0 digits). This returns an int when called with one argument,
    otherwise the same type as the number. ndigits may be negative.
 
    See the test_round method in future/tests/test_builtins.py for
    examples.
    """
    return_int = False
    if ndigits is None:
        return_int = True
        ndigits = 0
    if hasattr(number, '__round__'):
        return number.__round__(ndigits)
    
    if ndigits < 0:
        raise NotImplementedError('negative ndigits not supported yet')
    exponent = Decimal('10') ** (-ndigits)

    if PYPY:
        # Work around issue #24: round() breaks on PyPy with NumPy's types
        if 'numpy' in repr(type(number)):
            number = float(number)

    if not PY26:
        d = Decimal.from_float(number).quantize(exponent,
                                            rounding=ROUND_HALF_EVEN)
    else:
        d = from_float_26(number).quantize(exponent, rounding=ROUND_HALF_EVEN)

    if return_int:
        return int(d)
    else:
        return float(d)
 

### From Python 2.7's decimal.py. Only needed to support Py2.6: 
Example 32
Project: pype   Author: pypeclub   File: newround.py    MIT License 4 votes vote down vote up
def newround(number, ndigits=None):
    """
    See Python 3 documentation: uses Banker's Rounding.
 
    Delegates to the __round__ method if for some reason this exists.
 
    If not, rounds a number to a given precision in decimal digits (default
    0 digits). This returns an int when called with one argument,
    otherwise the same type as the number. ndigits may be negative.
 
    See the test_round method in future/tests/test_builtins.py for
    examples.
    """
    return_int = False
    if ndigits is None:
        return_int = True
        ndigits = 0
    if hasattr(number, '__round__'):
        return number.__round__(ndigits)
    
    if ndigits < 0:
        raise NotImplementedError('negative ndigits not supported yet')
    exponent = Decimal('10') ** (-ndigits)

    if PYPY:
        # Work around issue #24: round() breaks on PyPy with NumPy's types
        if 'numpy' in repr(type(number)):
            number = float(number)

    if not PY26:
        d = Decimal.from_float(number).quantize(exponent,
                                            rounding=ROUND_HALF_EVEN)
    else:
        d = from_float_26(number).quantize(exponent, rounding=ROUND_HALF_EVEN)

    if return_int:
        return int(d)
    else:
        return float(d)
 

### From Python 2.7's decimal.py. Only needed to support Py2.6: 
Example 33
Project: addon   Author: alfa-addon   File: newround.py    GNU General Public License v3.0 4 votes vote down vote up
def newround(number, ndigits=None):
    """
    See Python 3 documentation: uses Banker's Rounding.

    Delegates to the __round__ method if for some reason this exists.

    If not, rounds a number to a given precision in decimal digits (default
    0 digits). This returns an int when called with one argument,
    otherwise the same type as the number. ndigits may be negative.

    See the test_round method in future/tests/test_builtins.py for
    examples.
    """
    return_int = False
    if ndigits is None:
        return_int = True
        ndigits = 0
    if hasattr(number, '__round__'):
        return number.__round__(ndigits)

    if ndigits < 0:
        raise NotImplementedError('negative ndigits not supported yet')
    exponent = Decimal('10') ** (-ndigits)

    if PYPY:
        # Work around issue #24: round() breaks on PyPy with NumPy's types
        if 'numpy' in repr(type(number)):
            number = float(number)

    if isinstance(number, Decimal):
        d = number
    else:
        if not PY26:
            d = Decimal.from_float(number).quantize(exponent,
                                                rounding=ROUND_HALF_EVEN)
        else:
            d = from_float_26(number).quantize(exponent, rounding=ROUND_HALF_EVEN)

    if return_int:
        return int(d)
    else:
        return float(d)


### From Python 2.7's decimal.py. Only needed to support Py2.6: 
Example 34
Project: Pizza-or-Not-a-Pizza   Author: mraza007   File: newround.py    MIT License 4 votes vote down vote up
def newround(number, ndigits=None):
    """
    See Python 3 documentation: uses Banker's Rounding.
 
    Delegates to the __round__ method if for some reason this exists.
 
    If not, rounds a number to a given precision in decimal digits (default
    0 digits). This returns an int when called with one argument,
    otherwise the same type as the number. ndigits may be negative.
 
    See the test_round method in future/tests/test_builtins.py for
    examples.
    """
    return_int = False
    if ndigits is None:
        return_int = True
        ndigits = 0
    if hasattr(number, '__round__'):
        return number.__round__(ndigits)
    
    if ndigits < 0:
        raise NotImplementedError('negative ndigits not supported yet')
    exponent = Decimal('10') ** (-ndigits)

    if PYPY:
        # Work around issue #24: round() breaks on PyPy with NumPy's types
        if 'numpy' in repr(type(number)):
            number = float(number)

    if not PY26:
        d = Decimal.from_float(number).quantize(exponent,
                                            rounding=ROUND_HALF_EVEN)
    else:
        d = from_float_26(number).quantize(exponent, rounding=ROUND_HALF_EVEN)

    if return_int:
        return int(d)
    else:
        return float(d)
 

### From Python 2.7's decimal.py. Only needed to support Py2.6: 
Example 35
Project: arkScript   Author: akbchris   File: newround.py    MIT License 4 votes vote down vote up
def newround(number, ndigits=None):
    """
    See Python 3 documentation: uses Banker's Rounding.

    Delegates to the __round__ method if for some reason this exists.

    If not, rounds a number to a given precision in decimal digits (default
    0 digits). This returns an int when called with one argument,
    otherwise the same type as the number. ndigits may be negative.

    See the test_round method in future/tests/test_builtins.py for
    examples.
    """
    return_int = False
    if ndigits is None:
        return_int = True
        ndigits = 0
    if hasattr(number, '__round__'):
        return number.__round__(ndigits)

    if ndigits < 0:
        raise NotImplementedError('negative ndigits not supported yet')
    exponent = Decimal('10') ** (-ndigits)

    if PYPY:
        # Work around issue #24: round() breaks on PyPy with NumPy's types
        if 'numpy' in repr(type(number)):
            number = float(number)

    if not PY26:
        d = Decimal.from_float(number).quantize(exponent,
                                            rounding=ROUND_HALF_EVEN)
    else:
        d = from_float_26(number).quantize(exponent, rounding=ROUND_HALF_EVEN)

    if return_int:
        return int(d)
    else:
        return float(d)


### From Python 2.7's decimal.py. Only needed to support Py2.6: 
Example 36
Project: laboratoria   Author: almeidaw   File: newround.py    Apache License 2.0 4 votes vote down vote up
def newround(number, ndigits=None):
    """
    See Python 3 documentation: uses Banker's Rounding.
 
    Delegates to the __round__ method if for some reason this exists.
 
    If not, rounds a number to a given precision in decimal digits (default
    0 digits). This returns an int when called with one argument,
    otherwise the same type as the number. ndigits may be negative.
 
    See the test_round method in future/tests/test_builtins.py for
    examples.
    """
    return_int = False
    if ndigits is None:
        return_int = True
        ndigits = 0
    if hasattr(number, '__round__'):
        return number.__round__(ndigits)
    
    if ndigits < 0:
        raise NotImplementedError('negative ndigits not supported yet')
    exponent = Decimal('10') ** (-ndigits)

    if PYPY:
        # Work around issue #24: round() breaks on PyPy with NumPy's types
        if 'numpy' in repr(type(number)):
            number = float(number)

    if not PY26:
        d = Decimal.from_float(number).quantize(exponent,
                                            rounding=ROUND_HALF_EVEN)
    else:
        d = from_float_26(number).quantize(exponent, rounding=ROUND_HALF_EVEN)

    if return_int:
        return int(d)
    else:
        return float(d)
 

### From Python 2.7's decimal.py. Only needed to support Py2.6: 
Example 37
Project: laboratoria   Author: almeidaw   File: newround.py    Apache License 2.0 4 votes vote down vote up
def newround(number, ndigits=None):
    """
    See Python 3 documentation: uses Banker's Rounding.
 
    Delegates to the __round__ method if for some reason this exists.
 
    If not, rounds a number to a given precision in decimal digits (default
    0 digits). This returns an int when called with one argument,
    otherwise the same type as the number. ndigits may be negative.
 
    See the test_round method in future/tests/test_builtins.py for
    examples.
    """
    return_int = False
    if ndigits is None:
        return_int = True
        ndigits = 0
    if hasattr(number, '__round__'):
        return number.__round__(ndigits)
    
    if ndigits < 0:
        raise NotImplementedError('negative ndigits not supported yet')
    exponent = Decimal('10') ** (-ndigits)

    if PYPY:
        # Work around issue #24: round() breaks on PyPy with NumPy's types
        if 'numpy' in repr(type(number)):
            number = float(number)

    if not PY26:
        d = Decimal.from_float(number).quantize(exponent,
                                            rounding=ROUND_HALF_EVEN)
    else:
        d = from_float_26(number).quantize(exponent, rounding=ROUND_HALF_EVEN)

    if return_int:
        return int(d)
    else:
        return float(d)
 

### From Python 2.7's decimal.py. Only needed to support Py2.6: