]> granicus.if.org Git - python/commitdiff
Add support for trunc().
authorRaymond Hettinger <python@rcn.com>
Thu, 24 Jan 2008 19:05:29 +0000 (19:05 +0000)
committerRaymond Hettinger <python@rcn.com>
Thu, 24 Jan 2008 19:05:29 +0000 (19:05 +0000)
Lib/decimal.py
Lib/test/test_decimal.py

index e624a6dbbec16f4be98da63d00ae1240c2adf2c8..eea9448f4317eba0e3b0c14b5b880fe73d0c6773 100644 (file)
@@ -1433,6 +1433,8 @@ class Decimal(object):
         else:
             return s*int(self._int[:self._exp] or '0')
 
+    __trunc__ = __int__
+
     def __long__(self):
         """Converts to a long.
 
index 2135637e9d87bd40c3864b6d24da570b84917158..0ea4a36b82b6ce73aba211516c740bdf6b209c78 100644 (file)
@@ -1151,6 +1151,7 @@ class DecimalUsabilityTest(unittest.TestCase):
         checkSameDec("__floordiv__", True)
         checkSameDec("__hash__")
         checkSameDec("__int__")
+        checkSameDec("__trunc__")
         checkSameDec("__long__")
         checkSameDec("__mod__", True)
         checkSameDec("__mul__", True)
@@ -1216,6 +1217,16 @@ class DecimalPythonAPItests(unittest.TestCase):
             r = d.to_integral(ROUND_DOWN)
             self.assertEqual(Decimal(int(d)), r)
 
+    def test_trunc(self):
+        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 to_integral in the ROUND_DOWN mode
+            d = Decimal(s)
+            r = d.to_integral(ROUND_DOWN)
+            self.assertEqual(Decimal(trunc(d)), r)
+
 class ContextAPItests(unittest.TestCase):
 
     def test_pickle(self):