summaryrefslogtreecommitdiffstats
path: root/Lib
diff options
context:
space:
mode:
authorRaymond Hettinger <python@rcn.com>2010-04-02 16:58:27 (GMT)
committerRaymond Hettinger <python@rcn.com>2010-04-02 16:58:27 (GMT)
commit967985989031ecfa1dab7dd4dc757d6d33c47157 (patch)
tree198889b00fedd199dc75467d32b92501e7c8b5af /Lib
parent63b4355c75d51ef3133464ae04adb94c5be9047a (diff)
downloadcpython-967985989031ecfa1dab7dd4dc757d6d33c47157.zip
cpython-967985989031ecfa1dab7dd4dc757d6d33c47157.tar.gz
cpython-967985989031ecfa1dab7dd4dc757d6d33c47157.tar.bz2
Issue 8257: Decimal constructor to accept float argument.
Diffstat (limited to 'Lib')
-rw-r--r--Lib/decimal.py8
-rw-r--r--Lib/test/test_decimal.py26
2 files changed, 32 insertions, 2 deletions
diff --git a/Lib/decimal.py b/Lib/decimal.py
index 370eb82..ab38ed4 100644
--- a/Lib/decimal.py
+++ b/Lib/decimal.py
@@ -648,8 +648,12 @@ class Decimal(object):
return self
if isinstance(value, float):
- raise TypeError("Cannot convert float in Decimal constructor. "
- "Use from_float class method.")
+ value = Decimal.from_float(value)
+ self._exp = value._exp
+ self._sign = value._sign
+ self._int = value._int
+ self._is_special = value._is_special
+ return self
raise TypeError("Cannot convert %r to Decimal" % value)
diff --git a/Lib/test/test_decimal.py b/Lib/test/test_decimal.py
index 360a5e8..51bdf9c 100644
--- a/Lib/test/test_decimal.py
+++ b/Lib/test/test_decimal.py
@@ -52,6 +52,11 @@ def init():
)
setcontext(DefaultTestContext)
+# decorator for skipping tests on non-IEEE 754 platforms
+requires_IEEE_754 = unittest.skipUnless(
+ float.__getformat__("double").startswith("IEEE"),
+ "test requires IEEE 754 doubles")
+
TESTDATADIR = 'decimaltestdata'
if __name__ == '__main__':
file = sys.argv[0]
@@ -504,6 +509,27 @@ class DecimalExplicitConstructionTest(unittest.TestCase):
self.assertEqual(str(e), '0')
self.assertNotEqual(id(d), id(e))
+ @requires_IEEE_754
+ def test_explicit_from_float(self):
+ r = Decimal(0.1)
+ self.assertEqual(type(r), Decimal)
+ self.assertEqual(str(r),
+ '0.1000000000000000055511151231257827021181583404541015625')
+ self.assertTrue(Decimal(float('nan')).is_qnan())
+ self.assertTrue(Decimal(float('inf')).is_infinite())
+ self.assertTrue(Decimal(float('-inf')).is_infinite())
+ self.assertEqual(str(Decimal(float('nan'))),
+ str(Decimal('NaN')))
+ self.assertEqual(str(Decimal(float('inf'))),
+ str(Decimal('Infinity')))
+ self.assertEqual(str(Decimal(float('-inf'))),
+ str(Decimal('-Infinity')))
+ self.assertEqual(str(Decimal(float('-0.0'))),
+ str(Decimal('-0')))
+ for i in range(200):
+ x = random.expovariate(0.01) * (random.random() * 2.0 - 1.0)
+ self.assertEqual(x, float(Decimal(x))) # roundtrip
+
def test_explicit_context_create_decimal(self):
nc = copy.copy(getcontext())