From a4911b9dd748aac4a419455a2bc94f270f050528 Mon Sep 17 00:00:00 2001 From: Kayne Barclay Date: Thu, 19 Dec 2019 13:18:35 -0800 Subject: [PATCH] #322 Add support for negative ndigits in round; additionally, fixing a bug so that it handles passing in Decimal properly --- src/future/builtins/newround.py | 17 ++++++++++------- tests/test_future/test_builtins.py | 1 - 2 files changed, 10 insertions(+), 8 deletions(-) diff --git a/src/future/builtins/newround.py b/src/future/builtins/newround.py index 394a2c63..e2976a76 100644 --- a/src/future/builtins/newround.py +++ b/src/future/builtins/newround.py @@ -2,6 +2,7 @@ ``python-future``: pure Python implementation of Python 3 round(). """ +from __future__ import division from future.utils import PYPY, PY26, bind_method # Use the decimal module for simplicity of implementation (and @@ -29,8 +30,6 @@ def newround(number, ndigits=None): if hasattr(number, '__round__'): return number.__round__(ndigits) - if ndigits < 0: - raise NotImplementedError('negative ndigits not supported yet') exponent = Decimal('10') ** (-ndigits) if PYPY: @@ -42,15 +41,19 @@ def newround(number, ndigits=None): d = number else: if not PY26: - d = Decimal.from_float(number).quantize(exponent, - rounding=ROUND_HALF_EVEN) + d = Decimal.from_float(number) else: - d = from_float_26(number).quantize(exponent, rounding=ROUND_HALF_EVEN) + d = from_float_26(number) + + if ndigits < 0: + result = newround(d / exponent) * exponent + else: + result = d.quantize(exponent, rounding=ROUND_HALF_EVEN) if return_int: - return int(d) + return int(result) else: - return float(d) + return float(result) ### From Python 2.7's decimal.py. Only needed to support Py2.6: diff --git a/tests/test_future/test_builtins.py b/tests/test_future/test_builtins.py index ca07b9ef..3921a608 100644 --- a/tests/test_future/test_builtins.py +++ b/tests/test_future/test_builtins.py @@ -146,7 +146,6 @@ def test_round(self): self.assertTrue(isinstance(round(123.5, 0), float)) self.assertTrue(isinstance(round(123.5), Integral)) - @unittest.skip('negative ndigits not implemented yet') def test_round_negative_ndigits(self): self.assertEqual(round(10.1350, 0), 10.0) self.assertEqual(round(10.1350, -1), 10.0)