Commits

Ronald Oussoren committed cd55664

Allow *explicit* conversion from float to NSDecimal.

Comments (0)

Files changed (2)

pyobjc/Lib/Foundation/test/test_nsdecimal.py

         self.assertEquals(str(o), "-1234")
 
         o = NSDecimal(1L << 64 - 1)
-
-        self.assertRaises(TypeError, NSDecimal, 1.2)
+        
+        # This is wrong, explict conversion should be allowed!
+        #self.assertRaises(TypeError, NSDecimal, 1.2)
         self.assertRaises(OverflowError, NSDecimal, 1L << 128)
         self.assertRaises(OverflowError, NSDecimal, -1L << 128)
 
         self.assertRaises(TypeError, int, o)
         self.assertRaises(TypeError, float, o)
 
+    def testCreateFromFloat(self):
+        o = NSDecimal(1.1)
+        self.assertEquals(o.as_float(), 1.1)
+
 class TestNSDecimalNumber (unittest.TestCase):
     def testCreation1(self):
         o = NSDecimalNumber.decimalNumberWithString_("1.1234")
         self.assertRaises(TypeError, operator.add, o, 1.2)
         self.assertRaises(TypeError, operator.add, 1.2, o)
 
+        o = NSDecimalNumber.zero()
+        self.assertRaises(TypeError, operator.add, o, 1.2)
+
     def testSubtraction(self):
         r = NSDecimal()
         o = NSDecimalNumber.decimalNumberWithDecimal_(NSDecimal(1))

pyobjc/Modules/Foundation/decimals.m

 					mantissa, 0, NO);
 				return 0;
 			}
+		} else if (PyFloat_Check(pyValue)) {
+			/* Explicit conversion from float to NSDecimal
+			 * first convert the float to a string using repr, that
+			 * is easier than extracting the components of the 
+			 * float.
+			 */
+			PyObject* strVal = PyObject_Repr(pyValue);
+
+			if (strVal == NULL) return -1;
+			
+			stringVal = PyObjC_PythonToId(strVal);
+			Py_DECREF(strVal);
+
+			NS_DURING
+				DecimalFromString(&Decimal_Value(self), stringVal, NULL);
+			NS_HANDLER
+				PyObjCErr_FromObjC(localException);
+			NS_ENDHANDLER
+
+			if (PyErr_Occurred()) return -1;
+			return 0;
+			
+
 		} else if (!PyString_Check(pyValue) && !PyUnicode_Check(pyValue)) {
 			PyErr_Format(PyExc_TypeError, "cannot convert object of %s to NSDecimal", pyValue->ob_type->tp_name);
 			return -1;
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.