From: Raymond Hettinger Date: Wed, 24 Nov 2004 07:28:48 +0000 (+0000) Subject: SF bug #1071588 coercing decimal to int doesn't work between -1 and 1 X-Git-Tag: v2.4~20 X-Git-Url: http://git.ipfire.org/gitweb.cgi?a=commitdiff_plain;h=605ed0248375bbf87bbd1d80afc7c6918fd3ce2b;p=thirdparty%2FPython%2Fcpython.git SF bug #1071588 coercing decimal to int doesn't work between -1 and 1 --- diff --git a/Lib/decimal.py b/Lib/decimal.py index 6ffbd1847007..f9c065f677db 100644 --- a/Lib/decimal.py +++ b/Lib/decimal.py @@ -1410,14 +1410,14 @@ class Decimal(object): return context._raise_error(InvalidContext) elif self._isinfinity(): raise OverflowError, "Cannot convert infinity to long" - if not self: - return 0 - sign = '-'*self._sign if self._exp >= 0: - s = sign + ''.join(map(str, self._int)) + '0'*self._exp - return int(s) - s = sign + ''.join(map(str, self._int))[:self._exp] - return int(s) + s = ''.join(map(str, self._int)) + '0'*self._exp + else: + s = ''.join(map(str, self._int))[:self._exp] + if s == '': + s = '0' + sign = '-'*self._sign + return int(sign + s) def __long__(self): """Converts to a long. diff --git a/Lib/test/test_decimal.py b/Lib/test/test_decimal.py index a4e4041c3110..06e8b9dd1c98 100644 --- a/Lib/test/test_decimal.py +++ b/Lib/test/test_decimal.py @@ -967,13 +967,13 @@ class DecimalPythonAPItests(unittest.TestCase): self.assertEqual(d, e) def test_int(self): - data = '1.0 1.1 1.9 2.0 0.0 -1.0 -1.1 -1.9 -2.0'.split() - for s in data: + for x in range(-250, 250): + s = '%0.2f' % (x / 100.0) # should work the same as for floats self.assertEqual(int(Decimal(s)), int(float(s))) - # should work the same as ROUND_DOWN + # should work the same as to_integral in the ROUND_DOWN mode d = Decimal(s) - r = Context(prec=1, rounding=ROUND_DOWN).create_decimal(s) + r = d.to_integral(ROUND_DOWN) self.assertEqual(Decimal(int(d)), r) class ContextAPItests(unittest.TestCase):