Code

Ticket #2365: DecimalField-FloatField.2.diff

File DecimalField-FloatField.2.diff, 143.4 KB (added by adurdin@…, 7 years ago)

Patch -- implements database FloatField and DecimalField, and supporting fields in oldforms and newforms, with tests.

Line 
1Index: django/oldforms/__init__.py
2===================================================================
3--- django/oldforms/__init__.py (revision 4439)
4+++ django/oldforms/__init__.py (working copy)
5@@ -745,14 +745,27 @@
6             raise validators.CriticalValidationError, gettext("Enter a whole number between 0 and 32,767.")
7 
8 class FloatField(TextField):
9+    def __init__(self, field_name, is_required=False, validator_list=None):
10+        if validator_list is None: validator_list = []
11+        validator_list = [validators.isValidFloat] + validator_list
12+        TextField.__init__(self, field_name, is_required=is_required, validator_list=validator_list)
13+
14+    def html2python(data):
15+        if data == '' or data is None:
16+            return None
17+        return float(data)
18+    html2python = staticmethod(html2python)
19+
20+class DecimalField(TextField):
21     def __init__(self, field_name, max_digits, decimal_places, is_required=False, validator_list=None):
22         if validator_list is None: validator_list = []
23         self.max_digits, self.decimal_places = max_digits, decimal_places
24-        validator_list = [self.isValidFloat] + validator_list
25-        TextField.__init__(self, field_name, max_digits+2, max_digits+2, is_required, validator_list)
26+        validator_list = [self.isValidDecimal] + validator_list
27+        # Initialise the TextField, making sure it's large enough to fit the number with a - sign and a decimal point.
28+        super(DecimalField, self).__init__(field_name, max_digits+2, max_digits+2, is_required, validator_list)
29 
30-    def isValidFloat(self, field_data, all_data):
31-        v = validators.IsValidFloat(self.max_digits, self.decimal_places)
32+    def isValidDecimal(self, field_data, all_data):
33+        v = validators.IsValidDecimal(self.max_digits, self.decimal_places)
34         try:
35             v(field_data, all_data)
36         except validators.ValidationError, e:
37@@ -761,7 +774,14 @@
38     def html2python(data):
39         if data == '' or data is None:
40             return None
41-        return float(data)
42+        try:
43+            import decimal
44+        except ImportError:
45+            from django.utils import decimal
46+        try:
47+            return decimal.Decimal(data)
48+        except decimal.InvalidOperation, e:
49+            raise ValueError, e
50     html2python = staticmethod(html2python)
51 
52 ####################
53Index: django/db/models/fields/__init__.py
54===================================================================
55--- django/db/models/fields/__init__.py (revision 4439)
56+++ django/db/models/fields/__init__.py (working copy)
57@@ -668,15 +668,76 @@
58     def get_manipulator_field_objs(self):
59         return [curry(oldforms.FilePathField, path=self.path, match=self.match, recursive=self.recursive)]
60 
61-class FloatField(Field):
62+class DecimalField(Field):
63     empty_strings_allowed = False
64     def __init__(self, verbose_name=None, name=None, max_digits=None, decimal_places=None, **kwargs):
65         self.max_digits, self.decimal_places = max_digits, decimal_places
66         Field.__init__(self, verbose_name, name, **kwargs)
67 
68+    def to_python(self, value):
69+        try:
70+            import decimal
71+        except ImportError:
72+            from django.utils import decimal
73+        try:
74+            return decimal.Decimal(value)
75+        except (decimal.InvalidOperation):
76+            raise validators.ValidationError, gettext("This value must be a decimal number.")
77+
78+    def _format(self, value):
79+        if isinstance(value, basestring):
80+            return value
81+        else:
82+            return self.format_number(value)
83+   
84+    def format_number(self, value):
85+        """Formats a number into a string with the requisite number of digits and decimal places."""
86+       
87+        num_chars = self.max_digits
88+        # Allow for a decimal point
89+        if self.decimal_places > 0:
90+            num_chars += 1
91+        # Allow for a minus sign
92+        if value < 0:
93+            num_chars += 1
94+       
95+        return "%.*f" % (self.decimal_places, value)
96+
97+    def get_db_prep_save(self, value):
98+        value = value # self._format(value)
99+        return super(DecimalField, self).get_db_prep_save(value)
100+
101+    def get_db_prep_lookup(self, lookup_type, value):
102+        if lookup_type == 'range':
103+            value = [self._format(v) for v in value]
104+        else:
105+            value = self._format(value)
106+        return super(DecimalField, self).get_db_prep_lookup(lookup_type, value)
107+
108     def get_manipulator_field_objs(self):
109-        return [curry(oldforms.FloatField, max_digits=self.max_digits, decimal_places=self.decimal_places)]
110+        return [curry(oldforms.DecimalField, max_digits=self.max_digits, decimal_places=self.decimal_places)]
111 
112+    def formfield(self, **kwargs):
113+        "Returns a django.newforms.Field instance for this database Field."
114+        defaults = {'required': not self.blank, 'label': capfirst(self.verbose_name),
115+            'max_digits': self.max_digits, 'decimal_places': self.decimal_places}
116+        defaults.update(kwargs)
117+        return forms.DecimalField(**defaults)
118+
119+class FloatField(Field):
120+    empty_strings_allowed = False
121+    def __init__(self, verbose_name=None, name=None, **kwargs):
122+        Field.__init__(self, verbose_name, name, **kwargs)
123+
124+    def get_manipulator_field_objs(self):
125+        return [oldforms.FloatField]
126+
127+    def formfield(self, **kwargs):
128+        "Returns a django.newforms.FloatField instance for this database Field."
129+        defaults = {'required': not self.blank, 'label': capfirst(self.verbose_name)}
130+        defaults.update(kwargs)
131+        return forms.FloatField(**defaults)
132+
133 class ImageField(FileField):
134     def __init__(self, verbose_name=None, name=None, width_field=None, height_field=None, **kwargs):
135         self.width_field, self.height_field = width_field, height_field
136Index: django/db/backends/ado_mssql/creation.py
137===================================================================
138--- django/db/backends/ado_mssql/creation.py    (revision 4439)
139+++ django/db/backends/ado_mssql/creation.py    (working copy)
140@@ -5,9 +5,10 @@
141     'CommaSeparatedIntegerField': 'varchar(%(maxlength)s)',
142     'DateField':         'smalldatetime',
143     'DateTimeField':     'smalldatetime',
144+    'DecimalField':      'numeric(%(max_digits)s, %(decimal_places)s)',
145     'FileField':         'varchar(100)',
146     'FilePathField':     'varchar(100)',
147-    'FloatField':        'numeric(%(max_digits)s, %(decimal_places)s)',
148+    'FloatField':        'double precision',
149     'ImageField':        'varchar(100)',
150     'IntegerField':      'int',
151     'IPAddressField':    'char(15)',
152Index: django/db/backends/postgresql/introspection.py
153===================================================================
154--- django/db/backends/postgresql/introspection.py      (revision 4439)
155+++ django/db/backends/postgresql/introspection.py      (working copy)
156@@ -79,5 +79,5 @@
157     1114: 'DateTimeField',
158     1184: 'DateTimeField',
159     1266: 'TimeField',
160-    1700: 'FloatField',
161+    1700: 'DecimalField',
162 }
163Index: django/db/backends/postgresql/creation.py
164===================================================================
165--- django/db/backends/postgresql/creation.py   (revision 4439)
166+++ django/db/backends/postgresql/creation.py   (working copy)
167@@ -9,9 +9,10 @@
168     'CommaSeparatedIntegerField': 'varchar(%(maxlength)s)',
169     'DateField':         'date',
170     'DateTimeField':     'timestamp with time zone',
171+    'DecimalField':      'numeric(%(max_digits)s, %(decimal_places)s)',
172     'FileField':         'varchar(100)',
173     'FilePathField':     'varchar(100)',
174-    'FloatField':        'numeric(%(max_digits)s, %(decimal_places)s)',
175+    'FloatField':        'double precision',
176     'ImageField':        'varchar(100)',
177     'IntegerField':      'integer',
178     'IPAddressField':    'inet',
179Index: django/db/backends/sqlite3/base.py
180===================================================================
181--- django/db/backends/sqlite3/base.py  (revision 4439)
182+++ django/db/backends/sqlite3/base.py  (working copy)
183@@ -17,6 +17,13 @@
184         module = 'sqlite3'
185     raise ImproperlyConfigured, "Error loading %s module: %s" % (module, e)
186 
187+try:
188+    # Only exists in Python 2.4+
189+    import decimal
190+except ImportError:
191+    # Import copy of decimal.py from Python 2.4
192+    from django.utils import decimal
193+
194 DatabaseError = Database.DatabaseError
195 
196 Database.register_converter("bool", lambda s: str(s) == '1')
197@@ -25,6 +32,8 @@
198 Database.register_converter("datetime", util.typecast_timestamp)
199 Database.register_converter("timestamp", util.typecast_timestamp)
200 Database.register_converter("TIMESTAMP", util.typecast_timestamp)
201+Database.register_converter("decimal", util.typecast_decimal)
202+Database.register_adapter(decimal.Decimal, util.rev_typecast_decimal)
203 
204 def utf8rowFactory(cursor, row):
205     def utf8(s):
206Index: django/db/backends/sqlite3/creation.py
207===================================================================
208--- django/db/backends/sqlite3/creation.py      (revision 4439)
209+++ django/db/backends/sqlite3/creation.py      (working copy)
210@@ -8,9 +8,10 @@
211     'CommaSeparatedIntegerField':   'varchar(%(maxlength)s)',
212     'DateField':                    'date',
213     'DateTimeField':                'datetime',
214+    'DecimalField':                 'decimal',
215     'FileField':                    'varchar(100)',
216     'FilePathField':                'varchar(100)',
217-    'FloatField':                   'numeric(%(max_digits)s, %(decimal_places)s)',
218+    'FloatField':                   'real',
219     'ImageField':                   'varchar(100)',
220     'IntegerField':                 'integer',
221     'IPAddressField':               'char(15)',
222Index: django/db/backends/util.py
223===================================================================
224--- django/db/backends/util.py  (revision 4439)
225+++ django/db/backends/util.py  (working copy)
226@@ -1,6 +1,13 @@
227 import datetime
228 from time import time
229 
230+try:
231+    # Only exists in Python 2.4+
232+    import decimal
233+except ImportError:
234+    # Import copy of decimal.py from Python 2.4
235+    from django.utils import decimal
236+
237 class CursorDebugWrapper(object):
238     def __init__(self, cursor, db):
239         self.cursor = cursor
240@@ -85,6 +92,10 @@
241     if not s: return False
242     return str(s)[0].lower() == 't'
243 
244+def typecast_decimal(s):
245+    if s is None: return None
246+    return decimal.Decimal(s)
247+
248 ###############################################
249 # Converters from Python to database (string) #
250 ###############################################
251@@ -92,6 +103,10 @@
252 def rev_typecast_boolean(obj, d):
253     return obj and '1' or '0'
254 
255+def rev_typecast_decimal(d):
256+    if d is None: return None
257+    return str(d)
258+
259 ##################################################################################
260 # Helper functions for dictfetch* for databases that don't natively support them #
261 ##################################################################################
262Index: django/db/backends/mysql/base.py
263===================================================================
264--- django/db/backends/mysql/base.py    (revision 4439)
265+++ django/db/backends/mysql/base.py    (working copy)
266@@ -23,6 +23,7 @@
267     FIELD_TYPE.DATETIME: util.typecast_timestamp,
268     FIELD_TYPE.DATE: util.typecast_date,
269     FIELD_TYPE.TIME: util.typecast_time,
270+    FIELD_TYPE.DECIMAL: util.typecast_decimal,
271 })
272 
273 # This should match the numerical portion of the version numbers (we can treat
274Index: django/db/backends/mysql/introspection.py
275===================================================================
276--- django/db/backends/mysql/introspection.py   (revision 4439)
277+++ django/db/backends/mysql/introspection.py   (working copy)
278@@ -76,7 +76,7 @@
279 DATA_TYPES_REVERSE = {
280     FIELD_TYPE.BLOB: 'TextField',
281     FIELD_TYPE.CHAR: 'CharField',
282-    FIELD_TYPE.DECIMAL: 'FloatField',
283+    FIELD_TYPE.DECIMAL: 'DecimalField',
284     FIELD_TYPE.DATE: 'DateField',
285     FIELD_TYPE.DATETIME: 'DateTimeField',
286     FIELD_TYPE.DOUBLE: 'FloatField',
287Index: django/db/backends/mysql/creation.py
288===================================================================
289--- django/db/backends/mysql/creation.py        (revision 4439)
290+++ django/db/backends/mysql/creation.py        (working copy)
291@@ -9,9 +9,10 @@
292     'CommaSeparatedIntegerField': 'varchar(%(maxlength)s)',
293     'DateField':         'date',
294     'DateTimeField':     'datetime',
295+    'DecimalField':      'decimal(%(max_digits)s, %(decimal_places)s)',
296     'FileField':         'varchar(100)',
297     'FilePathField':     'varchar(100)',
298-    'FloatField':        'numeric(%(max_digits)s, %(decimal_places)s)',
299+    'FloatField':        'double precision',
300     'ImageField':        'varchar(100)',
301     'IntegerField':      'integer',
302     'IPAddressField':    'char(15)',
303Index: django/db/backends/oracle/introspection.py
304===================================================================
305--- django/db/backends/oracle/introspection.py  (revision 4439)
306+++ django/db/backends/oracle/introspection.py  (working copy)
307@@ -46,5 +46,5 @@
308     1114: 'DateTimeField',
309     1184: 'DateTimeField',
310     1266: 'TimeField',
311-    1700: 'FloatField',
312+    1700: 'DecimalField',
313 }
314Index: django/db/backends/oracle/creation.py
315===================================================================
316--- django/db/backends/oracle/creation.py       (revision 4439)
317+++ django/db/backends/oracle/creation.py       (working copy)
318@@ -5,9 +5,10 @@
319     'CommaSeparatedIntegerField': 'varchar2(%(maxlength)s)',
320     'DateField':         'date',
321     'DateTimeField':     'date',
322+    'DecimalField':      'number(%(max_digits)s, %(decimal_places)s)',
323     'FileField':         'varchar2(100)',
324     'FilePathField':     'varchar2(100)',
325-    'FloatField':        'number(%(max_digits)s, %(decimal_places)s)',
326+    'FloatField':        'double precision',
327     'ImageField':        'varchar2(100)',
328     'IntegerField':      'integer',
329     'IPAddressField':    'char(15)',
330Index: django/db/backends/postgresql_psycopg2/introspection.py
331===================================================================
332--- django/db/backends/postgresql_psycopg2/introspection.py     (revision 4439)
333+++ django/db/backends/postgresql_psycopg2/introspection.py     (working copy)
334@@ -79,5 +79,5 @@
335     1114: 'DateTimeField',
336     1184: 'DateTimeField',
337     1266: 'TimeField',
338-    1700: 'FloatField',
339+    1700: 'DecimalField',
340 }
341Index: django/core/validators.py
342===================================================================
343--- django/core/validators.py   (revision 4439)
344+++ django/core/validators.py   (working copy)
345@@ -25,6 +25,7 @@
346     r"(^[-!#$%&'*+/=?^_`{}|~0-9A-Z]+(\.[-!#$%&'*+/=?^_`{}|~0-9A-Z]+)*"  # dot-atom
347     r'|^"([\001-\010\013\014\016-\037!#-\[\]-\177]|\\[\001-011\013\014\016-\177])*"' # quoted-string
348     r')@(?:[A-Z0-9-]+\.)+[A-Z]{2,6}$', re.IGNORECASE)  # domain
349+decimal_re = re.compile(r'^-?(?P<digits>\d+)(\.(?P<decimals>\d+))?$')
350 integer_re = re.compile(r'^-?\d+$')
351 ip4_re = re.compile(r'^(25[0-5]|2[0-4]\d|[0-1]?\d?\d)(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}$')
352 phone_re = re.compile(r'^[A-PR-Y0-9]{3}-[A-PR-Y0-9]{3}-[A-PR-Y0-9]{4}$', re.IGNORECASE)
353@@ -403,28 +404,35 @@
354         if val != int(val):
355             raise ValidationError, gettext("This value must be a power of %s.") % self.power_of
356 
357-class IsValidFloat(object):
358+class IsValidDecimal(object):
359     def __init__(self, max_digits, decimal_places):
360         self.max_digits, self.decimal_places = max_digits, decimal_places
361 
362     def __call__(self, field_data, all_data):
363-        data = str(field_data)
364-        try:
365-            float(data)
366-        except ValueError:
367+        match = decimal_re.search(str(field_data))
368+        if not match:
369             raise ValidationError, gettext("Please enter a valid decimal number.")
370-        # Negative floats require more space to input.
371-        max_allowed_length = data.startswith('-') and (self.max_digits + 2) or (self.max_digits + 1)
372-        if len(data) > max_allowed_length:
373+       
374+        digits = len(match.group('digits') or '')
375+        decimals = len(match.group('decimals') or '')
376+       
377+        if digits + decimals > self.max_digits:
378             raise ValidationError, ngettext("Please enter a valid decimal number with at most %s total digit.",
379                 "Please enter a valid decimal number with at most %s total digits.", self.max_digits) % self.max_digits
380-        if (not '.' in data and len(data) > (max_allowed_length - self.decimal_places - 1)) or ('.' in data and len(data) > (max_allowed_length - (self.decimal_places - len(data.split('.')[1])))):
381+        if digits > (self.max_digits - self.decimal_places):
382             raise ValidationError, ngettext( "Please enter a valid decimal number with a whole part of at most %s digit.",
383                 "Please enter a valid decimal number with a whole part of at most %s digits.", str(self.max_digits-self.decimal_places)) % str(self.max_digits-self.decimal_places)
384-        if '.' in data and len(data.split('.')[1]) > self.decimal_places:
385+        if decimals > self.decimal_places:
386             raise ValidationError, ngettext("Please enter a valid decimal number with at most %s decimal place.",
387                 "Please enter a valid decimal number with at most %s decimal places.", self.decimal_places) % self.decimal_places
388 
389+def isValidFloat(field_data, all_data):
390+    data = str(field_data)
391+    try:
392+        float(data)
393+    except ValueError:
394+        raise ValidationError, gettext("Please enter a valid floating point number.")
395+
396 class HasAllowableSize(object):
397     """
398     Checks that the file-upload field data is a certain size. min_size and
399Index: django/core/management.py
400===================================================================
401--- django/core/management.py   (revision 4439)
402+++ django/core/management.py   (working copy)
403@@ -804,7 +804,7 @@
404                 if field_type == 'CharField' and row[3]:
405                     extra_params['maxlength'] = row[3]
406 
407-                if field_type == 'FloatField':
408+                if field_type == 'DecimalField':
409                     extra_params['max_digits'] = row[4]
410                     extra_params['decimal_places'] = row[5]
411 
412@@ -879,11 +879,11 @@
413                 e.add(opts, '"%s": You can\'t use "id" as a field name, because each model automatically gets an "id" field if none of the fields have primary_key=True. You need to either remove/rename your "id" field or add primary_key=True to a field.' % f.name)
414             if isinstance(f, models.CharField) and f.maxlength in (None, 0):
415                 e.add(opts, '"%s": CharFields require a "maxlength" attribute.' % f.name)
416-            if isinstance(f, models.FloatField):
417+            if isinstance(f, models.DecimalField):
418                 if f.decimal_places is None:
419-                    e.add(opts, '"%s": FloatFields require a "decimal_places" attribute.' % f.name)
420+                    e.add(opts, '"%s": DecimalFields require a "decimal_places" attribute.' % f.name)
421                 if f.max_digits is None:
422-                    e.add(opts, '"%s": FloatFields require a "max_digits" attribute.' % f.name)
423+                    e.add(opts, '"%s": DecimalFields require a "max_digits" attribute.' % f.name)
424             if isinstance(f, models.FileField) and not f.upload_to:
425                 e.add(opts, '"%s": FileFields require an "upload_to" attribute.' % f.name)
426             if isinstance(f, models.ImageField):
427Index: django/newforms/fields.py
428===================================================================
429--- django/newforms/fields.py   (revision 4439)
430+++ django/newforms/fields.py   (working copy)
431@@ -17,6 +17,7 @@
432     'RegexField', 'EmailField', 'URLField', 'BooleanField',
433     'ChoiceField', 'NullBooleanField', 'MultipleChoiceField',
434     'ComboField', 'MultiValueField',
435+    'FloatField', 'DecimalField',
436     'SplitDateTimeField',
437 )
438 
439@@ -28,6 +29,11 @@
440 except NameError:
441     from sets import Set as set # Python 2.3 fallback
442 
443+try:
444+    from decimal import Decimal # Only available in Python 2.4+
445+except ImportError:
446+    from django.utils.decimal import Decimal # Use bundled version for Python 2.3
447+
448 class Field(object):
449     widget = TextInput # Default widget to use when rendering this type of Field.
450     hidden_widget = HiddenInput # Default widget to use when rendering this as "hidden".
451@@ -128,6 +134,67 @@
452             raise ValidationError(gettext(u'Ensure this value is greater than or equal to %s.') % self.min_value)
453         return value
454 
455+class FloatField(Field):
456+    def __init__(self, max_value=None, min_value=None, required=True, widget=None, label=None, initial=None):
457+        self.max_value, self.min_value = max_value, min_value
458+        Field.__init__(self, required, widget, label, initial)
459+       
460+    def clean(self, value):
461+        """
462+        Validates that float() can be called on the input. Returns a float.
463+        Returns None for empty values.
464+        """
465+        super(FloatField, self).clean(value)
466+        if not self.required and value in EMPTY_VALUES:
467+            return None
468+        try:
469+            value = float(value)
470+        except (ValueError, TypeError):
471+            raise ValidationError(gettext(u'Enter a number.'))
472+        if self.max_value is not None and value > self.max_value:
473+            raise ValidationError(gettext(u'Ensure this value is less than or equal to %s.') % self.max_value)
474+        if self.min_value is not None and value < self.min_value:
475+            raise ValidationError(gettext(u'Ensure this value is greater than or equal to %s.') % self.min_value)
476+        return value
477+
478+decimal_re = re.compile(r'^-?(?P<digits>\d+)(\.(?P<decimals>\d+))?$')
479+
480+class DecimalField(Field):
481+    def __init__(self, max_value=None, min_value=None, max_digits=None, decimal_places=None, required=True, widget=None, label=None, initial=None):
482+        self.max_value, self.min_value = max_value, min_value
483+        self.max_digits, self.decimal_places = max_digits, decimal_places
484+        Field.__init__(self, required, widget, label, initial)
485+       
486+    def clean(self, value):
487+        """
488+        Validates that the input is a decimal number. Returns a decimal.Decimal
489+        instance. Returns None for empty values. Ensures that there are no more
490+        than max_digits in the number, and no more than decimal_places digits
491+        after the decimal point.
492+        """
493+        super(DecimalField, self).clean(value)
494+        if not self.required and value in EMPTY_VALUES:
495+            return None
496+        value = value.strip()
497+        match = decimal_re.search(value)
498+        if not match:
499+            raise ValidationError(gettext(u'Enter a number.'))
500+        else:
501+            value = Decimal(value)
502+        digits = len(match.group('digits') or '')
503+        decimals = len(match.group('decimals') or '')
504+        if self.max_value is not None and value > self.max_value:
505+            raise ValidationError(gettext(u'Ensure this value is less than or equal to %s.') % self.max_value)
506+        if self.min_value is not None and value < self.min_value:
507+            raise ValidationError(gettext(u'Ensure this value is greater than or equal to %s.') % self.min_value)
508+        if self.max_digits is not None and (digits + decimals) > self.max_digits:
509+            raise ValidationError(gettext(u'Ensure that there are no more than %s digits in total.') % self.max_digits)
510+        if self.decimal_places is not None and decimals > self.decimal_places:
511+            raise ValidationError(gettext(u'Ensure that there are no more than %s decimal places.') % self.decimal_places)
512+        if self.max_digits is not None and self.decimal_places is not None and digits > (self.max_digits - self.decimal_places):
513+            raise ValidationError(gettext(u'Ensure that there are no more than %s digits before the decimal point.') % (self.max_digits - self.decimal_places))
514+        return value
515+
516 DEFAULT_DATE_INPUT_FORMATS = (
517     '%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y', # '2006-10-25', '10/25/2006', '10/25/06'
518     '%b %d %Y', '%b %d, %Y',            # 'Oct 25 2006', 'Oct 25, 2006'
519Index: django/contrib/admin/templatetags/admin_list.py
520===================================================================
521--- django/contrib/admin/templatetags/admin_list.py     (revision 4439)
522+++ django/contrib/admin/templatetags/admin_list.py     (working copy)
523@@ -157,8 +157,8 @@
524             # Booleans are special: We use images.
525             elif isinstance(f, models.BooleanField) or isinstance(f, models.NullBooleanField):
526                 result_repr = _boolean_icon(field_val)
527-            # FloatFields are special: Zero-pad the decimals.
528-            elif isinstance(f, models.FloatField):
529+            # DecimalFields are special: Zero-pad the decimals.
530+            elif isinstance(f, models.DecimalField):
531                 if field_val is not None:
532                     result_repr = ('%%.%sf' % f.decimal_places) % field_val
533                 else:
534Index: django/contrib/admin/views/doc.py
535===================================================================
536--- django/contrib/admin/views/doc.py   (revision 4439)
537+++ django/contrib/admin/views/doc.py   (working copy)
538@@ -294,10 +294,11 @@
539     'CommaSeparatedIntegerField': _('Comma-separated integers'),
540     'DateField'                 : _('Date (without time)'),
541     'DateTimeField'             : _('Date (with time)'),
542+    'DecimalField'              : _('Decimal number'),
543     'EmailField'                : _('E-mail address'),
544     'FileField'                 : _('File path'),
545     'FilePathField'             : _('File path'),
546-    'FloatField'                : _('Decimal number'),
547+    'FloatField'                : _('Floating point number'),
548     'ForeignKey'                : _('Integer'),
549     'ImageField'                : _('File path'),
550     'IntegerField'              : _('Integer'),
551Index: django/utils/decimal.py
552===================================================================
553--- django/utils/decimal.py     (revision 0)
554+++ django/utils/decimal.py     (revision 0)
555@@ -0,0 +1,3078 @@
556+# Copyright (c) 2004 Python Software Foundation.
557+# All rights reserved.
558+
559+# Written by Eric Price <eprice at tjhsst.edu>
560+#    and Facundo Batista <facundo at taniquetil.com.ar>
561+#    and Raymond Hettinger <python at rcn.com>
562+#    and Aahz <aahz at pobox.com>
563+#    and Tim Peters
564+
565+# This module is currently Py2.3 compatible and should be kept that way
566+# unless a major compelling advantage arises.  IOW, 2.3 compatibility is
567+# strongly preferred, but not guaranteed.
568+
569+# Also, this module should be kept in sync with the latest updates of
570+# the IBM specification as it evolves.  Those updates will be treated
571+# as bug fixes (deviation from the spec is a compatibility, usability
572+# bug) and will be backported.  At this point the spec is stabilizing
573+# and the updates are becoming fewer, smaller, and less significant.
574+
575+"""
576+This is a Py2.3 implementation of decimal floating point arithmetic based on
577+the General Decimal Arithmetic Specification:
578+
579+    www2.hursley.ibm.com/decimal/decarith.html
580+
581+and IEEE standard 854-1987:
582+
583+    www.cs.berkeley.edu/~ejr/projects/754/private/drafts/854-1987/dir.html
584+
585+Decimal floating point has finite precision with arbitrarily large bounds.
586+
587+The purpose of the module is to support arithmetic using familiar
588+"schoolhouse" rules and to avoid the some of tricky representation
589+issues associated with binary floating point.  The package is especially
590+useful for financial applications or for contexts where users have
591+expectations that are at odds with binary floating point (for instance,
592+in binary floating point, 1.00 % 0.1 gives 0.09999999999999995 instead
593+of the expected Decimal("0.00") returned by decimal floating point).
594+
595+Here are some examples of using the decimal module:
596+
597+>>> from decimal import *
598+>>> setcontext(ExtendedContext)
599+>>> Decimal(0)
600+Decimal("0")
601+>>> Decimal("1")
602+Decimal("1")
603+>>> Decimal("-.0123")
604+Decimal("-0.0123")
605+>>> Decimal(123456)
606+Decimal("123456")
607+>>> Decimal("123.45e12345678901234567890")
608+Decimal("1.2345E+12345678901234567892")
609+>>> Decimal("1.33") + Decimal("1.27")
610+Decimal("2.60")
611+>>> Decimal("12.34") + Decimal("3.87") - Decimal("18.41")
612+Decimal("-2.20")
613+>>> dig = Decimal(1)
614+>>> print dig / Decimal(3)
615+0.333333333
616+>>> getcontext().prec = 18
617+>>> print dig / Decimal(3)
618+0.333333333333333333
619+>>> print dig.sqrt()
620+1
621+>>> print Decimal(3).sqrt()
622+1.73205080756887729
623+>>> print Decimal(3) ** 123
624+4.85192780976896427E+58
625+>>> inf = Decimal(1) / Decimal(0)
626+>>> print inf
627+Infinity
628+>>> neginf = Decimal(-1) / Decimal(0)
629+>>> print neginf
630+-Infinity
631+>>> print neginf + inf
632+NaN
633+>>> print neginf * inf
634+-Infinity
635+>>> print dig / 0
636+Infinity
637+>>> getcontext().traps[DivisionByZero] = 1
638+>>> print dig / 0
639+Traceback (most recent call last):
640+  ...
641+  ...
642+  ...
643+DivisionByZero: x / 0
644+>>> c = Context()
645+>>> c.traps[InvalidOperation] = 0
646+>>> print c.flags[InvalidOperation]
647+0
648+>>> c.divide(Decimal(0), Decimal(0))
649+Decimal("NaN")
650+>>> c.traps[InvalidOperation] = 1
651+>>> print c.flags[InvalidOperation]
652+1
653+>>> c.flags[InvalidOperation] = 0
654+>>> print c.flags[InvalidOperation]
655+0
656+>>> print c.divide(Decimal(0), Decimal(0))
657+Traceback (most recent call last):
658+  ...
659+  ...
660+  ...
661+InvalidOperation: 0 / 0
662+>>> print c.flags[InvalidOperation]
663+1
664+>>> c.flags[InvalidOperation] = 0
665+>>> c.traps[InvalidOperation] = 0
666+>>> print c.divide(Decimal(0), Decimal(0))
667+NaN
668+>>> print c.flags[InvalidOperation]
669+1
670+>>>
671+"""
672+
673+__all__ = [
674+    # Two major classes
675+    'Decimal', 'Context',
676+
677+    # Contexts
678+    'DefaultContext', 'BasicContext', 'ExtendedContext',
679+
680+    # Exceptions
681+    'DecimalException', 'Clamped', 'InvalidOperation', 'DivisionByZero',
682+    'Inexact', 'Rounded', 'Subnormal', 'Overflow', 'Underflow',
683+
684+    # Constants for use in setting up contexts
685+    'ROUND_DOWN', 'ROUND_HALF_UP', 'ROUND_HALF_EVEN', 'ROUND_CEILING',
686+    'ROUND_FLOOR', 'ROUND_UP', 'ROUND_HALF_DOWN',
687+
688+    # Functions for manipulating contexts
689+    'setcontext', 'getcontext'
690+]
691+
692+import copy
693+
694+#Rounding
695+ROUND_DOWN = 'ROUND_DOWN'
696+ROUND_HALF_UP = 'ROUND_HALF_UP'
697+ROUND_HALF_EVEN = 'ROUND_HALF_EVEN'
698+ROUND_CEILING = 'ROUND_CEILING'
699+ROUND_FLOOR = 'ROUND_FLOOR'
700+ROUND_UP = 'ROUND_UP'
701+ROUND_HALF_DOWN = 'ROUND_HALF_DOWN'
702+
703+#Rounding decision (not part of the public API)
704+NEVER_ROUND = 'NEVER_ROUND'    # Round in division (non-divmod), sqrt ONLY
705+ALWAYS_ROUND = 'ALWAYS_ROUND'  # Every operation rounds at end.
706+
707+#Errors
708+
709+class DecimalException(ArithmeticError):
710+    """Base exception class.
711+
712+    Used exceptions derive from this.
713+    If an exception derives from another exception besides this (such as
714+    Underflow (Inexact, Rounded, Subnormal) that indicates that it is only
715+    called if the others are present.  This isn't actually used for
716+    anything, though.
717+
718+    handle  -- Called when context._raise_error is called and the
719+               trap_enabler is set.  First argument is self, second is the
720+               context.  More arguments can be given, those being after
721+               the explanation in _raise_error (For example,
722+               context._raise_error(NewError, '(-x)!', self._sign) would
723+               call NewError().handle(context, self._sign).)
724+
725+    To define a new exception, it should be sufficient to have it derive
726+    from DecimalException.
727+    """
728+    def handle(self, context, *args):
729+        pass
730+
731+
732+class Clamped(DecimalException):
733+    """Exponent of a 0 changed to fit bounds.
734+
735+    This occurs and signals clamped if the exponent of a result has been
736+    altered in order to fit the constraints of a specific concrete
737+    representation. This may occur when the exponent of a zero result would
738+    be outside the bounds of a representation, or  when a large normal
739+    number would have an encoded exponent that cannot be represented. In
740+    this latter case, the exponent is reduced to fit and the corresponding
741+    number of zero digits are appended to the coefficient ("fold-down").
742+    """
743+
744+
745+class InvalidOperation(DecimalException):
746+    """An invalid operation was performed.
747+
748+    Various bad things cause this:
749+
750+    Something creates a signaling NaN
751+    -INF + INF
752+     0 * (+-)INF
753+     (+-)INF / (+-)INF
754+    x % 0
755+    (+-)INF % x
756+    x._rescale( non-integer )
757+    sqrt(-x) , x > 0
758+    0 ** 0
759+    x ** (non-integer)
760+    x ** (+-)INF
761+    An operand is invalid
762+    """
763+    def handle(self, context, *args):
764+        if args:
765+            if args[0] == 1: #sNaN, must drop 's' but keep diagnostics
766+                return Decimal( (args[1]._sign, args[1]._int, 'n') )
767+        return NaN
768+
769+class ConversionSyntax(InvalidOperation):
770+    """Trying to convert badly formed string.
771+
772+    This occurs and signals invalid-operation if an string is being
773+    converted to a number and it does not conform to the numeric string
774+    syntax. The result is [0,qNaN].
775+    """
776+
777+    def handle(self, context, *args):
778+        return (0, (0,), 'n') #Passed to something which uses a tuple.
779+
780+class DivisionByZero(DecimalException, ZeroDivisionError):
781+    """Division by 0.
782+
783+    This occurs and signals division-by-zero if division of a finite number
784+    by zero was attempted (during a divide-integer or divide operation, or a
785+    power operation with negative right-hand operand), and the dividend was
786+    not zero.
787+
788+    The result of the operation is [sign,inf], where sign is the exclusive
789+    or of the signs of the operands for divide, or is 1 for an odd power of
790+    -0, for power.
791+    """
792+
793+    def handle(self, context, sign, double = None, *args):
794+        if double is not None:
795+            return (Infsign[sign],)*2
796+        return Infsign[sign]
797+
798+class DivisionImpossible(InvalidOperation):
799+    """Cannot perform the division adequately.
800+
801+    This occurs and signals invalid-operation if the integer result of a
802+    divide-integer or remainder operation had too many digits (would be
803+    longer than precision). The result is [0,qNaN].
804+    """
805+
806+    def handle(self, context, *args):
807+        return (NaN, NaN)
808+
809+class DivisionUndefined(InvalidOperation, ZeroDivisionError):
810+    """Undefined result of division.
811+
812+    This occurs and signals invalid-operation if division by zero was
813+    attempted (during a divide-integer, divide, or remainder operation), and
814+    the dividend is also zero. The result is [0,qNaN].
815+    """
816+
817+    def handle(self, context, tup=None, *args):
818+        if tup is not None:
819+            return (NaN, NaN) #for 0 %0, 0 // 0
820+        return NaN
821+
822+class Inexact(DecimalException):
823+    """Had to round, losing information.
824+
825+    This occurs and signals inexact whenever the result of an operation is
826+    not exact (that is, it needed to be rounded and any discarded digits
827+    were non-zero), or if an overflow or underflow condition occurs. The
828+    result in all cases is unchanged.
829+
830+    The inexact signal may be tested (or trapped) to determine if a given
831+    operation (or sequence of operations) was inexact.
832+    """
833+    pass
834+
835+class InvalidContext(InvalidOperation):
836+    """Invalid context.  Unknown rounding, for example.
837+
838+    This occurs and signals invalid-operation if an invalid context was
839+    detected during an operation. This can occur if contexts are not checked
840+    on creation and either the precision exceeds the capability of the
841+    underlying concrete representation or an unknown or unsupported rounding
842+    was specified. These aspects of the context need only be checked when
843+    the values are required to be used. The result is [0,qNaN].
844+    """
845+
846+    def handle(self, context, *args):
847+        return NaN
848+
849+class Rounded(DecimalException):
850+    """Number got rounded (not  necessarily changed during rounding).
851+
852+    This occurs and signals rounded whenever the result of an operation is
853+    rounded (that is, some zero or non-zero digits were discarded from the
854+    coefficient), or if an overflow or underflow condition occurs. The
855+    result in all cases is unchanged.
856+
857+    The rounded signal may be tested (or trapped) to determine if a given
858+    operation (or sequence of operations) caused a loss of precision.
859+    """
860+    pass
861+
862+class Subnormal(DecimalException):
863+    """Exponent < Emin before rounding.
864+
865+    This occurs and signals subnormal whenever the result of a conversion or
866+    operation is subnormal (that is, its adjusted exponent is less than
867+    Emin, before any rounding). The result in all cases is unchanged.
868+
869+    The subnormal signal may be tested (or trapped) to determine if a given
870+    or operation (or sequence of operations) yielded a subnormal result.
871+    """
872+    pass
873+
874+class Overflow(Inexact, Rounded):
875+    """Numerical overflow.
876+
877+    This occurs and signals overflow if the adjusted exponent of a result
878+    (from a conversion or from an operation that is not an attempt to divide
879+    by zero), after rounding, would be greater than the largest value that
880+    can be handled by the implementation (the value Emax).
881+
882+    The result depends on the rounding mode:
883+
884+    For round-half-up and round-half-even (and for round-half-down and
885+    round-up, if implemented), the result of the operation is [sign,inf],
886+    where sign is the sign of the intermediate result. For round-down, the
887+    result is the largest finite number that can be represented in the
888+    current precision, with the sign of the intermediate result. For
889+    round-ceiling, the result is the same as for round-down if the sign of
890+    the intermediate result is 1, or is [0,inf] otherwise. For round-floor,
891+    the result is the same as for round-down if the sign of the intermediate
892+    result is 0, or is [1,inf] otherwise. In all cases, Inexact and Rounded
893+    will also be raised.
894+   """
895+
896+    def handle(self, context, sign, *args):
897+        if context.rounding in (ROUND_HALF_UP, ROUND_HALF_EVEN,
898+                                     ROUND_HALF_DOWN, ROUND_UP):
899+            return Infsign[sign]
900+        if sign == 0:
901+            if context.rounding == ROUND_CEILING:
902+                return Infsign[sign]
903+            return Decimal((sign, (9,)*context.prec,
904+                            context.Emax-context.prec+1))
905+        if sign == 1:
906+            if context.rounding == ROUND_FLOOR:
907+                return Infsign[sign]
908+            return Decimal( (sign, (9,)*context.prec,
909+                             context.Emax-context.prec+1))
910+
911+
912+class Underflow(Inexact, Rounded, Subnormal):
913+    """Numerical underflow with result rounded to 0.
914+
915+    This occurs and signals underflow if a result is inexact and the
916+    adjusted exponent of the result would be smaller (more negative) than
917+    the smallest value that can be handled by the implementation (the value
918+    Emin). That is, the result is both inexact and subnormal.
919+
920+    The result after an underflow will be a subnormal number rounded, if
921+    necessary, so that its exponent is not less than Etiny. This may result
922+    in 0 with the sign of the intermediate result and an exponent of Etiny.
923+
924+    In all cases, Inexact, Rounded, and Subnormal will also be raised.
925+    """
926+
927+# List of public traps and flags
928+_signals = [Clamped, DivisionByZero, Inexact, Overflow, Rounded,
929+           Underflow, InvalidOperation, Subnormal]
930+
931+# Map conditions (per the spec) to signals
932+_condition_map = {ConversionSyntax:InvalidOperation,
933+                  DivisionImpossible:InvalidOperation,
934+                  DivisionUndefined:InvalidOperation,
935+                  InvalidContext:InvalidOperation}
936+
937+##### Context Functions #######################################
938+
939+# The getcontext() and setcontext() function manage access to a thread-local
940+# current context.  Py2.4 offers direct support for thread locals.  If that
941+# is not available, use threading.currentThread() which is slower but will
942+# work for older Pythons.  If threads are not part of the build, create a
943+# mock threading object with threading.local() returning the module namespace.
944+
945+try:
946+    import threading
947+except ImportError:
948+    # Python was compiled without threads; create a mock object instead
949+    import sys
950+    class MockThreading:
951+        def local(self, sys=sys):
952+            return sys.modules[__name__]
953+    threading = MockThreading()
954+    del sys, MockThreading
955+
956+try:
957+    threading.local
958+
959+except AttributeError:
960+
961+    #To fix reloading, force it to create a new context
962+    #Old contexts have different exceptions in their dicts, making problems.
963+    if hasattr(threading.currentThread(), '__decimal_context__'):
964+        del threading.currentThread().__decimal_context__
965+
966+    def setcontext(context):
967+        """Set this thread's context to context."""
968+        if context in (DefaultContext, BasicContext, ExtendedContext):
969+            context = context.copy()
970+            context.clear_flags()
971+        threading.currentThread().__decimal_context__ = context
972+
973+    def getcontext():
974+        """Returns this thread's context.
975+
976+        If this thread does not yet have a context, returns
977+        a new context and sets this thread's context.
978+        New contexts are copies of DefaultContext.
979+        """
980+        try:
981+            return threading.currentThread().__decimal_context__
982+        except AttributeError:
983+            context = Context()
984+            threading.currentThread().__decimal_context__ = context
985+            return context
986+
987+else:
988+
989+    local = threading.local()
990+    if hasattr(local, '__decimal_context__'):
991+        del local.__decimal_context__
992+
993+    def getcontext(_local=local):
994+        """Returns this thread's context.
995+
996+        If this thread does not yet have a context, returns
997+        a new context and sets this thread's context.
998+        New contexts are copies of DefaultContext.
999+        """
1000+        try:
1001+            return _local.__decimal_context__
1002+        except AttributeError:
1003+            context = Context()
1004+            _local.__decimal_context__ = context
1005+            return context
1006+
1007+    def setcontext(context, _local=local):
1008+        """Set this thread's context to context."""
1009+        if context in (DefaultContext, BasicContext, ExtendedContext):
1010+            context = context.copy()
1011+            context.clear_flags()
1012+        _local.__decimal_context__ = context
1013+
1014+    del threading, local        # Don't contaminate the namespace
1015+
1016+
1017+##### Decimal class ###########################################
1018+
1019+class Decimal(object):
1020+    """Floating point class for decimal arithmetic."""
1021+
1022+    __slots__ = ('_exp','_int','_sign', '_is_special')
1023+    # Generally, the value of the Decimal instance is given by
1024+    #  (-1)**_sign * _int * 10**_exp
1025+    # Special values are signified by _is_special == True
1026+
1027+    # We're immutable, so use __new__ not __init__
1028+    def __new__(cls, value="0", context=None):
1029+        """Create a decimal point instance.
1030+
1031+        >>> Decimal('3.14')              # string input
1032+        Decimal("3.14")
1033+        >>> Decimal((0, (3, 1, 4), -2))  # tuple input (sign, digit_tuple, exponent)
1034+        Decimal("3.14")
1035+        >>> Decimal(314)                 # int or long
1036+        Decimal("314")
1037+        >>> Decimal(Decimal(314))        # another decimal instance
1038+        Decimal("314")
1039+        """
1040+
1041+        self = object.__new__(cls)
1042+        self._is_special = False
1043+
1044+        # From an internal working value
1045+        if isinstance(value, _WorkRep):
1046+            self._sign = value.sign
1047+            self._int = tuple(map(int, str(value.int)))
1048+            self._exp = int(value.exp)
1049+            return self
1050+
1051+        # From another decimal
1052+        if isinstance(value, Decimal):
1053+            self._exp  = value._exp
1054+            self._sign = value._sign
1055+            self._int  = value._int
1056+            self._is_special  = value._is_special
1057+            return self
1058+
1059+        # From an integer
1060+        if isinstance(value, (int,long)):
1061+            if value >= 0:
1062+                self._sign = 0
1063+            else:
1064+                self._sign = 1
1065+            self._exp = 0
1066+            self._int = tuple(map(int, str(abs(value))))
1067+            return self
1068+
1069+        # tuple/list conversion (possibly from as_tuple())
1070+        if isinstance(value, (list,tuple)):
1071+            if len(value) != 3:
1072+                raise ValueError, 'Invalid arguments'
1073+            if value[0] not in [0,1]:
1074+                raise ValueError, 'Invalid sign'
1075+            for digit in value[1]:
1076+                if not isinstance(digit, (int,long)) or digit < 0:
1077+                    raise ValueError, "The second value in the tuple must be composed of non negative integer elements."
1078+
1079+            self._sign = value[0]
1080+            self._int  = tuple(value[1])
1081+            if value[2] in ('F','n','N'):
1082+                self._exp = value[2]
1083+                self._is_special = True
1084+            else:
1085+                self._exp  = int(value[2])
1086+            return self
1087+
1088+        if isinstance(value, float):
1089+            raise TypeError("Cannot convert float to Decimal.  " +
1090+                            "First convert the float to a string")
1091+
1092+        # Other argument types may require the context during interpretation
1093+        if context is None:
1094+            context = getcontext()
1095+
1096+        # From a string
1097+        # REs insist on real strings, so we can too.
1098+        if isinstance(value, basestring):
1099+            if _isinfinity(value):
1100+                self._exp = 'F'
1101+                self._int = (0,)
1102+                self._is_special = True
1103+                if _isinfinity(value) == 1:
1104+                    self._sign = 0
1105+                else:
1106+                    self._sign = 1
1107+                return self
1108+            if _isnan(value):
1109+                sig, sign, diag = _isnan(value)
1110+                self._is_special = True
1111+                if len(diag) > context.prec: #Diagnostic info too long
1112+                    self._sign, self._int, self._exp = \
1113+                                context._raise_error(ConversionSyntax)
1114+                    return self
1115+                if sig == 1:
1116+                    self._exp = 'n' #qNaN
1117+                else: #sig == 2
1118+                    self._exp = 'N' #sNaN
1119+                self._sign = sign
1120+                self._int = tuple(map(int, diag)) #Diagnostic info
1121+                return self
1122+            try:
1123+                self._sign, self._int, self._exp = _string2exact(value)
1124+            except ValueError:
1125+                self._is_special = True
1126+                self._sign, self._int, self._exp = context._raise_error(ConversionSyntax)
1127+            return self
1128+
1129+        raise TypeError("Cannot convert %r to Decimal" % value)
1130+
1131+    def _isnan(self):
1132+        """Returns whether the number is not actually one.
1133+
1134+        0 if a number
1135+        1 if NaN
1136+        2 if sNaN
1137+        """
1138+        if self._is_special:
1139+            exp = self._exp
1140+            if exp == 'n':
1141+                return 1
1142+            elif exp == 'N':
1143+                return 2
1144+        return 0
1145+
1146+    def _isinfinity(self):
1147+        """Returns whether the number is infinite
1148+
1149+        0 if finite or not a number
1150+        1 if +INF
1151+        -1 if -INF
1152+        """
1153+        if self._exp == 'F':
1154+            if self._sign:
1155+                return -1
1156+            return 1
1157+        return 0
1158+
1159+    def _check_nans(self, other = None, context=None):
1160+        """Returns whether the number is not actually one.
1161+
1162+        if self, other are sNaN, signal
1163+        if self, other are NaN return nan
1164+        return 0
1165+
1166+        Done before operations.
1167+        """
1168+
1169+        self_is_nan = self._isnan()
1170+        if other is None:
1171+            other_is_nan = False
1172+        else:
1173+            other_is_nan = other._isnan()
1174+
1175+        if self_is_nan or other_is_nan:
1176+            if context is None:
1177+                context = getcontext()
1178+
1179+            if self_is_nan == 2:
1180+                return context._raise_error(InvalidOperation, 'sNaN',
1181+                                        1, self)
1182+            if other_is_nan == 2:
1183+                return context._raise_error(InvalidOperation, 'sNaN',
1184+                                        1, other)
1185+            if self_is_nan:
1186+                return self
1187+
1188+            return other
1189+        return 0
1190+
1191+    def __nonzero__(self):
1192+        """Is the number non-zero?
1193+
1194+        0 if self == 0
1195+        1 if self != 0
1196+        """
1197+        if self._is_special:
1198+            return 1
1199+        return sum(self._int) != 0
1200+
1201+    def __cmp__(self, other, context=None):
1202+        other = _convert_other(other)
1203+        if other is NotImplemented:
1204+            return other
1205+
1206+        if self._is_special or other._is_special:
1207+            ans = self._check_nans(other, context)
1208+            if ans:
1209+                return 1 # Comparison involving NaN's always reports self > other
1210+
1211+            # INF = INF
1212+            return cmp(self._isinfinity(), other._isinfinity())
1213+
1214+        if not self and not other:
1215+            return 0 #If both 0, sign comparison isn't certain.
1216+
1217+        #If different signs, neg one is less
1218+        if other._sign < self._sign:
1219+            return -1
1220+        if self._sign < other._sign:
1221+            return 1
1222+
1223+        self_adjusted = self.adjusted()
1224+        other_adjusted = other.adjusted()
1225+        if self_adjusted == other_adjusted and \
1226+           self._int + (0,)*(self._exp - other._exp) == \
1227+           other._int + (0,)*(other._exp - self._exp):
1228+            return 0 #equal, except in precision. ([0]*(-x) = [])
1229+        elif self_adjusted > other_adjusted and self._int[0] != 0:
1230+            return (-1)**self._sign
1231+        elif self_adjusted < other_adjusted and other._int[0] != 0:
1232+            return -((-1)**self._sign)
1233+
1234+        # Need to round, so make sure we have a valid context
1235+        if context is None:
1236+            context = getcontext()
1237+
1238+        context = context._shallow_copy()
1239+        rounding = context._set_rounding(ROUND_UP) #round away from 0
1240+
1241+        flags = context._ignore_all_flags()
1242+        res = self.__sub__(other, context=context)
1243+
1244+        context._regard_flags(*flags)
1245+
1246+        context.rounding = rounding
1247+
1248+        if not res:
1249+            return 0
1250+        elif res._sign:
1251+            return -1
1252+        return 1
1253+
1254+    def __eq__(self, other):
1255+        if not isinstance(other, (Decimal, int, long)):
1256+            return NotImplemented
1257+        return self.__cmp__(other) == 0
1258+
1259+    def __ne__(self, other):
1260+        if not isinstance(other, (Decimal, int, long)):
1261+            return NotImplemented
1262+        return self.__cmp__(other) != 0
1263+
1264+    def compare(self, other, context=None):
1265+        """Compares one to another.
1266+
1267+        -1 => a < b
1268+        0  => a = b
1269+        1  => a > b
1270+        NaN => one is NaN
1271+        Like __cmp__, but returns Decimal instances.
1272+        """
1273+        other = _convert_other(other)
1274+        if other is NotImplemented:
1275+            return other
1276+
1277+        #compare(NaN, NaN) = NaN
1278+        if (self._is_special or other and other._is_special):
1279+            ans = self._check_nans(other, context)
1280+            if ans:
1281+                return ans
1282+
1283+        return Decimal(self.__cmp__(other, context))
1284+
1285+    def __hash__(self):
1286+        """x.__hash__() <==> hash(x)"""
1287+        # Decimal integers must hash the same as the ints
1288+        # Non-integer decimals are normalized and hashed as strings
1289+        # Normalization assures that hast(100E-1) == hash(10)
1290+        if self._is_special:
1291+            if self._isnan():
1292+                raise TypeError('Cannot hash a NaN value.')
1293+            return hash(str(self))
1294+        i = int(self)
1295+        if self == Decimal(i):
1296+            return hash(i)
1297+        assert self.__nonzero__()   # '-0' handled by integer case
1298+        return hash(str(self.normalize()))
1299+
1300+    def as_tuple(self):
1301+        """Represents the number as a triple tuple.
1302+
1303+        To show the internals exactly as they are.
1304+        """
1305+        return (self._sign, self._int, self._exp)
1306+
1307+    def __repr__(self):
1308+        """Represents the number as an instance of Decimal."""
1309+        # Invariant:  eval(repr(d)) == d
1310+        return 'Decimal("%s")' % str(self)
1311+
1312+    def __str__(self, eng = 0, context=None):
1313+        """Return string representation of the number in scientific notation.
1314+
1315+        Captures all of the information in the underlying representation.
1316+        """
1317+
1318+        if self._isnan():
1319+            minus = '-'*self._sign
1320+            if self._int == (0,):
1321+                info = ''
1322+            else:
1323+                info = ''.join(map(str, self._int))
1324+            if self._isnan() == 2:
1325+                return minus + 'sNaN' + info
1326+            return minus + 'NaN' + info
1327+        if self._isinfinity():
1328+            minus = '-'*self._sign
1329+            return minus + 'Infinity'
1330+
1331+        if context is None:
1332+            context = getcontext()
1333+
1334+        tmp = map(str, self._int)
1335+        numdigits = len(self._int)
1336+        leftdigits = self._exp + numdigits
1337+        if eng and not self: #self = 0eX wants 0[.0[0]]eY, not [[0]0]0eY
1338+            if self._exp < 0 and self._exp >= -6: #short, no need for e/E
1339+                s = '-'*self._sign + '0.' + '0'*(abs(self._exp))
1340+                return s
1341+            #exp is closest mult. of 3 >= self._exp
1342+            exp = ((self._exp - 1)// 3 + 1) * 3
1343+            if exp != self._exp:
1344+                s = '0.'+'0'*(exp - self._exp)
1345+            else:
1346+                s = '0'
1347+            if exp != 0:
1348+                if context.capitals:
1349+                    s += 'E'
1350+                else:
1351+                    s += 'e'
1352+                if exp > 0:
1353+                    s += '+' #0.0e+3, not 0.0e3
1354+                s += str(exp)
1355+            s = '-'*self._sign + s
1356+            return s
1357+        if eng:
1358+            dotplace = (leftdigits-1)%3+1
1359+            adjexp = leftdigits -1 - (leftdigits-1)%3
1360+        else:
1361+            adjexp = leftdigits-1
1362+            dotplace = 1
1363+        if self._exp == 0:
1364+            pass
1365+        elif self._exp < 0 and adjexp >= 0:
1366+            tmp.insert(leftdigits, '.')
1367+        elif self._exp < 0 and adjexp >= -6:
1368+            tmp[0:0] = ['0'] * int(-leftdigits)
1369+            tmp.insert(0, '0.')
1370+        else:
1371+            if numdigits > dotplace:
1372+                tmp.insert(dotplace, '.')
1373+            elif numdigits < dotplace:
1374+                tmp.extend(['0']*(dotplace-numdigits))
1375+            if adjexp:
1376+                if not context.capitals:
1377+                    tmp.append('e')
1378+                else:
1379+                    tmp.append('E')
1380+                    if adjexp > 0:
1381+                        tmp.append('+')
1382+                tmp.append(str(adjexp))
1383+        if eng:
1384+            while tmp[0:1] == ['0']:
1385+                tmp[0:1] = []
1386+            if len(tmp) == 0 or tmp[0] == '.' or tmp[0].lower() == 'e':
1387+                tmp[0:0] = ['0']
1388+        if self._sign:
1389+            tmp.insert(0, '-')
1390+
1391+        return ''.join(tmp)
1392+
1393+    def to_eng_string(self, context=None):
1394+        """Convert to engineering-type string.
1395+
1396+        Engineering notation has an exponent which is a multiple of 3, so there
1397+        are up to 3 digits left of the decimal place.
1398+
1399+        Same rules for when in exponential and when as a value as in __str__.
1400+        """
1401+        return self.__str__(eng=1, context=context)
1402+
1403+    def __neg__(self, context=None):
1404+        """Returns a copy with the sign switched.
1405+
1406+        Rounds, if it has reason.
1407+        """
1408+        if self._is_special:
1409+            ans = self._check_nans(context=context)
1410+            if ans:
1411+                return ans
1412+
1413+        if not self:
1414+            # -Decimal('0') is Decimal('0'), not Decimal('-0')
1415+            sign = 0
1416+        elif self._sign:
1417+            sign = 0
1418+        else:
1419+            sign = 1
1420+
1421+        if context is None:
1422+            context = getcontext()
1423+        if context._rounding_decision == ALWAYS_ROUND:
1424+            return Decimal((sign, self._int, self._exp))._fix(context)
1425+        return Decimal( (sign, self._int, self._exp))
1426+
1427+    def __pos__(self, context=None):
1428+        """Returns a copy, unless it is a sNaN.
1429+
1430+        Rounds the number (if more then precision digits)
1431+        """
1432+        if self._is_special:
1433+            ans = self._check_nans(context=context)
1434+            if ans:
1435+                return ans
1436+
1437+        sign = self._sign
1438+        if not self:
1439+            # + (-0) = 0
1440+            sign = 0
1441+
1442+        if context is None:
1443+            context = getcontext()
1444+
1445+        if context._rounding_decision == ALWAYS_ROUND:
1446+            ans = self._fix(context)
1447+        else:
1448+            ans = Decimal(self)
1449+        ans._sign = sign
1450+        return ans
1451+
1452+    def __abs__(self, round=1, context=None):
1453+        """Returns the absolute value of self.
1454+
1455+        If the second argument is 0, do not round.
1456+        """
1457+        if self._is_special:
1458+            ans = self._check_nans(context=context)
1459+            if ans:
1460+                return ans
1461+
1462+        if not round:
1463+            if context is None:
1464+                context = getcontext()
1465+            context = context._shallow_copy()
1466+            context._set_rounding_decision(NEVER_ROUND)
1467+
1468+        if self._sign:
1469+            ans = self.__neg__(context=context)
1470+        else:
1471+            ans = self.__pos__(context=context)
1472+
1473+        return ans
1474+
1475+    def __add__(self, other, context=None):
1476+        """Returns self + other.
1477+
1478+        -INF + INF (or the reverse) cause InvalidOperation errors.
1479+        """
1480+        other = _convert_other(other)
1481+        if other is NotImplemented:
1482+            return other
1483+
1484+        if context is None:
1485+            context = getcontext()
1486+
1487+        if self._is_special or other._is_special:
1488+            ans = self._check_nans(other, context)
1489+            if ans:
1490+                return ans
1491+
1492+            if self._isinfinity():
1493+                #If both INF, same sign => same as both, opposite => error.
1494+                if self._sign != other._sign and other._isinfinity():
1495+                    return context._raise_error(InvalidOperation, '-INF + INF')
1496+                return Decimal(self)
1497+            if other._isinfinity():
1498+                return Decimal(other)  #Can't both be infinity here
1499+
1500+        shouldround = context._rounding_decision == ALWAYS_ROUND
1501+
1502+        exp = min(self._exp, other._exp)
1503+        negativezero = 0
1504+        if context.rounding == ROUND_FLOOR and self._sign != other._sign:
1505+            #If the answer is 0, the sign should be negative, in this case.
1506+            negativezero = 1
1507+
1508+        if not self and not other:
1509+            sign = min(self._sign, other._sign)
1510+            if negativezero:
1511+                sign = 1
1512+            return Decimal( (sign, (0,), exp))
1513+        if not self:
1514+            exp = max(exp, other._exp - context.prec-1)
1515+            ans = other._rescale(exp, watchexp=0, context=context)
1516+            if shouldround:
1517+                ans = ans._fix(context)
1518+            return ans
1519+        if not other:
1520+            exp = max(exp, self._exp - context.prec-1)
1521+            ans = self._rescale(exp, watchexp=0, context=context)
1522+            if shouldround:
1523+                ans = ans._fix(context)
1524+            return ans
1525+
1526+        op1 = _WorkRep(self)
1527+        op2 = _WorkRep(other)
1528+        op1, op2 = _normalize(op1, op2, shouldround, context.prec)
1529+
1530+        result = _WorkRep()
1531+        if op1.sign != op2.sign:
1532+            # Equal and opposite
1533+            if op1.int == op2.int:
1534+                if exp < context.Etiny():
1535+                    exp = context.Etiny()
1536+                    context._raise_error(Clamped)
1537+                return Decimal((negativezero, (0,), exp))
1538+            if op1.int < op2.int:
1539+                op1, op2 = op2, op1
1540+                #OK, now abs(op1) > abs(op2)
1541+            if op1.sign == 1:
1542+                result.sign = 1
1543+                op1.sign, op2.sign = op2.sign, op1.sign
1544+            else:
1545+                result.sign = 0
1546+                #So we know the sign, and op1 > 0.
1547+        elif op1.sign == 1:
1548+            result.sign = 1
1549+            op1.sign, op2.sign = (0, 0)
1550+        else:
1551+            result.sign = 0
1552+        #Now, op1 > abs(op2) > 0
1553+
1554+        if op2.sign == 0:
1555+            result.int = op1.int + op2.int
1556+        else:
1557+            result.int = op1.int - op2.int
1558+
1559+        result.exp = op1.exp
1560+        ans = Decimal(result)
1561+        if shouldround:
1562+            ans = ans._fix(context)
1563+        return ans
1564+
1565+    __radd__ = __add__
1566+
1567+    def __sub__(self, other, context=None):
1568+        """Return self + (-other)"""
1569+        other = _convert_other(other)
1570+        if other is NotImplemented:
1571+            return other
1572+
1573+        if self._is_special or other._is_special:
1574+            ans = self._check_nans(other, context=context)
1575+            if ans:
1576+                return ans
1577+
1578+        # -Decimal(0) = Decimal(0), which we don't want since
1579+        # (-0 - 0 = -0 + (-0) = -0, but -0 + 0 = 0.)
1580+        # so we change the sign directly to a copy
1581+        tmp = Decimal(other)
1582+        tmp._sign = 1-tmp._sign
1583+
1584+        return self.__add__(tmp, context=context)
1585+
1586+    def __rsub__(self, other, context=None):
1587+        """Return other + (-self)"""
1588+        other = _convert_other(other)
1589+        if other is NotImplemented:
1590+            return other
1591+
1592+        tmp = Decimal(self)
1593+        tmp._sign = 1 - tmp._sign
1594+        return other.__add__(tmp, context=context)
1595+
1596+    def _increment(self, round=1, context=None):
1597+        """Special case of add, adding 1eExponent
1598+
1599+        Since it is common, (rounding, for example) this adds
1600+        (sign)*one E self._exp to the number more efficiently than add.
1601+
1602+        For example:
1603+        Decimal('5.624e10')._increment() == Decimal('5.625e10')
1604+        """
1605+        if self._is_special:
1606+            ans = self._check_nans(context=context)
1607+            if ans:
1608+                return ans
1609+
1610+            return Decimal(self) # Must be infinite, and incrementing makes no difference
1611+
1612+        L = list(self._int)
1613+        L[-1] += 1
1614+        spot = len(L)-1
1615+        while L[spot] == 10:
1616+            L[spot] = 0
1617+            if spot == 0:
1618+                L[0:0] = [1]
1619+                break
1620+            L[spot-1] += 1
1621+            spot -= 1
1622+        ans = Decimal((self._sign, L, self._exp))
1623+
1624+        if context is None:
1625+            context = getcontext()
1626+        if round and context._rounding_decision == ALWAYS_ROUND:
1627+            ans = ans._fix(context)
1628+        return ans
1629+
1630+    def __mul__(self, other, context=None):
1631+        """Return self * other.
1632+
1633+        (+-) INF * 0 (or its reverse) raise InvalidOperation.
1634+        """
1635+        other = _convert_other(other)
1636+        if other is NotImplemented:
1637+            return other
1638+
1639+        if context is None:
1640+            context = getcontext()
1641+
1642+        resultsign = self._sign ^ other._sign
1643+
1644+        if self._is_special or other._is_special:
1645+            ans = self._check_nans(other, context)
1646+            if ans:
1647+                return ans
1648+
1649+            if self._isinfinity():
1650+                if not other:
1651+                    return context._raise_error(InvalidOperation, '(+-)INF * 0')
1652+                return Infsign[resultsign]
1653+
1654+            if other._isinfinity():
1655+                if not self:
1656+                    return context._raise_error(InvalidOperation, '0 * (+-)INF')
1657+                return Infsign[resultsign]
1658+
1659+        resultexp = self._exp + other._exp
1660+        shouldround = context._rounding_decision == ALWAYS_ROUND
1661+
1662+        # Special case for multiplying by zero
1663+        if not self or not other:
1664+            ans = Decimal((resultsign, (0,), resultexp))
1665+            if shouldround:
1666+                #Fixing in case the exponent is out of bounds
1667+                ans = ans._fix(context)
1668+            return ans
1669+
1670+        # Special case for multiplying by power of 10
1671+        if self._int == (1,):
1672+            ans = Decimal((resultsign, other._int, resultexp))
1673+            if shouldround:
1674+                ans = ans._fix(context)
1675+            return ans
1676+        if other._int == (1,):
1677+            ans = Decimal((resultsign, self._int, resultexp))
1678+            if shouldround:
1679+                ans = ans._fix(context)
1680+            return ans
1681+
1682+        op1 = _WorkRep(self)
1683+        op2 = _WorkRep(other)
1684+
1685+        ans = Decimal( (resultsign, map(int, str(op1.int * op2.int)), resultexp))
1686+        if shouldround:
1687+            ans = ans._fix(context)
1688+
1689+        return ans
1690+    __rmul__ = __mul__
1691+
1692+    def __div__(self, other, context=None):
1693+        """Return self / other."""
1694+        return self._divide(other, context=context)
1695+    __truediv__ = __div__
1696+
1697+    def _divide(self, other, divmod = 0, context=None):
1698+        """Return a / b, to context.prec precision.
1699+
1700+        divmod:
1701+        0 => true division
1702+        1 => (a //b, a%b)
1703+        2 => a //b
1704+        3 => a%b
1705+
1706+        Actually, if divmod is 2 or 3 a tuple is returned, but errors for
1707+        computing the other value are not raised.
1708+        """
1709+        other = _convert_other(other)
1710+        if other is NotImplemented:
1711+            if divmod in (0, 1):
1712+                return NotImplemented
1713+            return (NotImplemented, NotImplemented)
1714+
1715+        if context is None:
1716+            context = getcontext()
1717+
1718+        sign = self._sign ^ other._sign
1719+
1720+        if self._is_special or other._is_special:
1721+            ans = self._check_nans(other, context)
1722+            if ans:
1723+                if divmod:
1724+                    return (ans, ans)
1725+                return ans
1726+
1727+            if self._isinfinity() and other._isinfinity():
1728+                if divmod:
1729+                    return (context._raise_error(InvalidOperation,
1730+                                            '(+-)INF // (+-)INF'),
1731+                            context._raise_error(InvalidOperation,
1732+                                            '(+-)INF % (+-)INF'))
1733+                return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF')
1734+
1735+            if self._isinfinity():
1736+                if divmod == 1:
1737+                    return (Infsign[sign],
1738+                            context._raise_error(InvalidOperation, 'INF % x'))
1739+                elif divmod == 2:
1740+                    return (Infsign[sign], NaN)
1741+                elif divmod == 3:
1742+                    return (Infsign[sign],
1743+                            context._raise_error(InvalidOperation, 'INF % x'))
1744+                return Infsign[sign]
1745+
1746+            if other._isinfinity():
1747+                if divmod:
1748+                    return (Decimal((sign, (0,), 0)), Decimal(self))
1749+                context._raise_error(Clamped, 'Division by infinity')
1750+                return Decimal((sign, (0,), context.Etiny()))
1751+
1752+        # Special cases for zeroes
1753+        if not self and not other:
1754+            if divmod:
1755+                return context._raise_error(DivisionUndefined, '0 / 0', 1)
1756+            return context._raise_error(DivisionUndefined, '0 / 0')
1757+
1758+        if not self:
1759+            if divmod:
1760+                otherside = Decimal(self)
1761+                otherside._exp = min(self._exp, other._exp)
1762+                return (Decimal((sign, (0,), 0)),  otherside)
1763+            exp = self._exp - other._exp
1764+            if exp < context.Etiny():
1765+                exp = context.Etiny()
1766+                context._raise_error(Clamped, '0e-x / y')
1767+            if exp > context.Emax:
1768+                exp = context.Emax
1769+                context._raise_error(Clamped, '0e+x / y')
1770+            return Decimal( (sign, (0,), exp) )
1771+
1772+        if not other:
1773+            if divmod:
1774+                return context._raise_error(DivisionByZero, 'divmod(x,0)',
1775+                                           sign, 1)
1776+            return context._raise_error(DivisionByZero, 'x / 0', sign)
1777+
1778+        #OK, so neither = 0, INF or NaN
1779+
1780+        shouldround = context._rounding_decision == ALWAYS_ROUND
1781+
1782+        #If we're dividing into ints, and self < other, stop.
1783+        #self.__abs__(0) does not round.
1784+        if divmod and (self.__abs__(0, context) < other.__abs__(0, context)):
1785+
1786+            if divmod == 1 or divmod == 3:
1787+                exp = min(self._exp, other._exp)
1788+                ans2 = self._rescale(exp, context=context, watchexp=0)
1789+                if shouldround:
1790+                    ans2 = ans2._fix(context)
1791+                return (Decimal( (sign, (0,), 0) ),
1792+                        ans2)
1793+
1794+            elif divmod == 2:
1795+                #Don't round the mod part, if we don't need it.
1796+                return (Decimal( (sign, (0,), 0) ), Decimal(self))
1797+
1798+        op1 = _WorkRep(self)
1799+        op2 = _WorkRep(other)
1800+        op1, op2, adjust = _adjust_coefficients(op1, op2)
1801+        res = _WorkRep( (sign, 0, (op1.exp - op2.exp)) )
1802+        if divmod and res.exp > context.prec + 1:
1803+            return context._raise_error(DivisionImpossible)
1804+
1805+        prec_limit = 10 ** context.prec
1806+        while 1:
1807+            while op2.int <= op1.int:
1808+                res.int += 1
1809+                op1.int -= op2.int
1810+            if res.exp == 0 and divmod:
1811+                if res.int >= prec_limit and shouldround:
1812+                    return context._raise_error(DivisionImpossible)
1813+                otherside = Decimal(op1)
1814+                frozen = context._ignore_all_flags()
1815+
1816+                exp = min(self._exp, other._exp)
1817+                otherside = otherside._rescale(exp, context=context, watchexp=0)
1818+                context._regard_flags(*frozen)
1819+                if shouldround:
1820+                    otherside = otherside._fix(context)
1821+                return (Decimal(res), otherside)
1822+
1823+            if op1.int == 0 and adjust >= 0 and not divmod:
1824+                break
1825+            if res.int >= prec_limit and shouldround:
1826+                if divmod:
1827+                    return context._raise_error(DivisionImpossible)
1828+                shouldround=1
1829+                # Really, the answer is a bit higher, so adding a one to
1830+                # the end will make sure the rounding is right.
1831+                if op1.int != 0:
1832+                    res.int *= 10
1833+                    res.int += 1
1834+                    res.exp -= 1
1835+
1836+                break
1837+            res.int *= 10
1838+            res.exp -= 1
1839+            adjust += 1
1840+            op1.int *= 10
1841+            op1.exp -= 1
1842+
1843+            if res.exp == 0 and divmod and op2.int > op1.int:
1844+                #Solves an error in precision.  Same as a previous block.
1845+
1846+                if res.int >= prec_limit and shouldround:
1847+                    return context._raise_error(DivisionImpossible)
1848+                otherside = Decimal(op1)
1849+                frozen = context._ignore_all_flags()
1850+
1851+                exp = min(self._exp, other._exp)
1852+                otherside = otherside._rescale(exp, context=context)
1853+
1854+                context._regard_flags(*frozen)
1855+
1856+                return (Decimal(res), otherside)
1857+
1858+        ans = Decimal(res)
1859+        if shouldround:
1860+            ans = ans._fix(context)
1861+        return ans
1862+
1863+    def __rdiv__(self, other, context=None):
1864+        """Swaps self/other and returns __div__."""
1865+        other = _convert_other(other)
1866+        if other is NotImplemented:
1867+            return other
1868+        return other.__div__(self, context=context)
1869+    __rtruediv__ = __rdiv__
1870+
1871+    def __divmod__(self, other, context=None):
1872+        """
1873+        (self // other, self % other)
1874+        """
1875+        return self._divide(other, 1, context)
1876+
1877+    def __rdivmod__(self, other, context=None):
1878+        """Swaps self/other and returns __divmod__."""
1879+        other = _convert_other(other)
1880+        if other is NotImplemented:
1881+            return other
1882+        return other.__divmod__(self, context=context)
1883+
1884+    def __mod__(self, other, context=None):
1885+        """
1886+        self % other
1887+        """
1888+        other = _convert_other(other)
1889+        if other is NotImplemented:
1890+            return other
1891+
1892+        if self._is_special or other._is_special:
1893+            ans = self._check_nans(other, context)
1894+            if ans:
1895+                return ans
1896+
1897+        if self and not other:
1898+            return context._raise_error(InvalidOperation, 'x % 0')
1899+
1900+        return self._divide(other, 3, context)[1]
1901+
1902+    def __rmod__(self, other, context=None):
1903+        """Swaps self/other and returns __mod__."""
1904+        other = _convert_other(other)
1905+        if other is NotImplemented:
1906+            return other
1907+        return other.__mod__(self, context=context)
1908+
1909+    def remainder_near(self, other, context=None):
1910+        """
1911+        Remainder nearest to 0-  abs(remainder-near) <= other/2
1912+        """
1913+        other = _convert_other(other)
1914+        if other is NotImplemented:
1915+            return other
1916+
1917+        if self._is_special or other._is_special:
1918+            ans = self._check_nans(other, context)
1919+            if ans:
1920+                return ans
1921+        if self and not other:
1922+            return context._raise_error(InvalidOperation, 'x % 0')
1923+
1924+        if context is None:
1925+            context = getcontext()
1926+        # If DivisionImpossible causes an error, do not leave Rounded/Inexact
1927+        # ignored in the calling function.
1928+        context = context._shallow_copy()
1929+        flags = context._ignore_flags(Rounded, Inexact)
1930+        #keep DivisionImpossible flags
1931+        (side, r) = self.__divmod__(other, context=context)
1932+
1933+        if r._isnan():
1934+            context._regard_flags(*flags)
1935+            return r
1936+
1937+        context = context._shallow_copy()
1938+        rounding = context._set_rounding_decision(NEVER_ROUND)
1939+
1940+        if other._sign:
1941+            comparison = other.__div__(Decimal(-2), context=context)
1942+        else:
1943+            comparison = other.__div__(Decimal(2), context=context)
1944+
1945+        context._set_rounding_decision(rounding)
1946+        context._regard_flags(*flags)
1947+
1948+        s1, s2 = r._sign, comparison._sign
1949+        r._sign, comparison._sign = 0, 0
1950+
1951+        if r < comparison:
1952+            r._sign, comparison._sign = s1, s2
1953+            #Get flags now
1954+            self.__divmod__(other, context=context)
1955+            return r._fix(context)
1956+        r._sign, comparison._sign = s1, s2
1957+
1958+        rounding = context._set_rounding_decision(NEVER_ROUND)
1959+
1960+        (side, r) = self.__divmod__(other, context=context)
1961+        context._set_rounding_decision(rounding)
1962+        if r._isnan():
1963+            return r
1964+
1965+        decrease = not side._iseven()
1966+        rounding = context._set_rounding_decision(NEVER_ROUND)
1967+        side = side.__abs__(context=context)
1968+        context._set_rounding_decision(rounding)
1969+
1970+        s1, s2 = r._sign, comparison._sign
1971+        r._sign, comparison._sign = 0, 0
1972+        if r > comparison or decrease and r == comparison:
1973+            r._sign, comparison._sign = s1, s2
1974+            context.prec += 1
1975+            if len(side.__add__(Decimal(1), context=context)._int) >= context.prec:
1976+                context.prec -= 1
1977+                return context._raise_error(DivisionImpossible)[1]
1978+            context.prec -= 1
1979+            if self._sign == other._sign:
1980+                r = r.__sub__(other, context=context)
1981+            else:
1982+                r = r.__add__(other, context=context)
1983+        else:
1984+            r._sign, comparison._sign = s1, s2
1985+
1986+        return r._fix(context)
1987+
1988+    def __floordiv__(self, other, context=None):
1989+        """self // other"""
1990+        return self._divide(other, 2, context)[0]
1991+
1992+    def __rfloordiv__(self, other, context=None):
1993+        """Swaps self/other and returns __floordiv__."""
1994+        other = _convert_other(other)
1995+        if other is NotImplemented:
1996+            return other
1997+        return other.__floordiv__(self, context=context)
1998+
1999+    def __float__(self):
2000+        """Float representation."""
2001+        return float(str(self))
2002+
2003+    def __int__(self):
2004+        """Converts self to a int, truncating if necessary."""
2005+        if self._is_special:
2006+            if self._isnan():
2007+                context = getcontext()
2008+                return context._raise_error(InvalidContext)
2009+            elif self._isinfinity():
2010+                raise OverflowError, "Cannot convert infinity to long"
2011+        if self._exp >= 0:
2012+            s = ''.join(map(str, self._int)) + '0'*self._exp
2013+        else:
2014+            s = ''.join(map(str, self._int))[:self._exp]
2015+        if s == '':
2016+            s = '0'
2017+        sign = '-'*self._sign
2018+        return int(sign + s)
2019+
2020+    def __long__(self):
2021+        """Converts to a long.
2022+
2023+        Equivalent to long(int(self))
2024+        """
2025+        return long(self.__int__())
2026+
2027+    def _fix(self, context):
2028+        """Round if it is necessary to keep self within prec precision.
2029+
2030+        Rounds and fixes the exponent.  Does not raise on a sNaN.
2031+
2032+        Arguments:
2033+        self - Decimal instance
2034+        context - context used.
2035+        """
2036+        if self._is_special:
2037+            return self
2038+        if context is None:
2039+            context = getcontext()
2040+        prec = context.prec
2041+        ans = self._fixexponents(context)
2042+        if len(ans._int) > prec:
2043+            ans = ans._round(prec, context=context)
2044+            ans = ans._fixexponents(context)
2045+        return ans
2046+
2047+    def _fixexponents(self, context):
2048+        """Fix the exponents and return a copy with the exponent in bounds.
2049+        Only call if known to not be a special value.
2050+        """
2051+        folddown = context._clamp
2052+        Emin = context.Emin
2053+        ans = self
2054+        ans_adjusted = ans.adjusted()
2055+        if ans_adjusted < Emin:
2056+            Etiny = context.Etiny()
2057+            if ans._exp < Etiny:
2058+                if not ans:
2059+                    ans = Decimal(self)
2060+                    ans._exp = Etiny
2061+                    context._raise_error(Clamped)
2062+                    return ans
2063+                ans = ans._rescale(Etiny, context=context)
2064+                #It isn't zero, and exp < Emin => subnormal
2065+                context._raise_error(Subnormal)
2066+                if context.flags[Inexact]:
2067+                    context._raise_error(Underflow)
2068+            else:
2069+                if ans:
2070+                    #Only raise subnormal if non-zero.
2071+                    context._raise_error(Subnormal)
2072+        else:
2073+            Etop = context.Etop()
2074+            if folddown and ans._exp > Etop:
2075+                context._raise_error(Clamped)
2076+                ans = ans._rescale(Etop, context=context)
2077+            else:
2078+                Emax = context.Emax
2079+                if ans_adjusted > Emax:
2080+                    if not ans:
2081+                        ans = Decimal(self)
2082+                        ans._exp = Emax
2083+                        context._raise_error(Clamped)
2084+                        return ans
2085+                    context._raise_error(Inexact)
2086+                    context._raise_error(Rounded)
2087+                    return context._raise_error(Overflow, 'above Emax', ans._sign)
2088+        return ans
2089+
2090+    def _round(self, prec=None, rounding=None, context=None):
2091+        """Returns a rounded version of self.
2092+
2093+        You can specify the precision or rounding method.  Otherwise, the
2094+        context determines it.
2095+        """
2096+
2097+        if self._is_special:
2098+            ans = self._check_nans(context=context)
2099+            if ans:
2100+                return ans
2101+
2102+            if self._isinfinity():
2103+                return Decimal(self)
2104+
2105+        if context is None:
2106+            context = getcontext()
2107+
2108+        if rounding is None:
2109+            rounding = context.rounding
2110+        if prec is None:
2111+            prec = context.prec
2112+
2113+        if not self:
2114+            if prec <= 0:
2115+                dig = (0,)
2116+                exp = len(self._int) - prec + self._exp
2117+            else:
2118+                dig = (0,) * prec
2119+                exp = len(self._int) + self._exp - prec
2120+            ans = Decimal((self._sign, dig, exp))
2121+            context._raise_error(Rounded)
2122+            return ans
2123+
2124+        if prec == 0:
2125+            temp = Decimal(self)
2126+            temp._int = (0,)+temp._int
2127+            prec = 1
2128+        elif prec < 0:
2129+            exp = self._exp + len(self._int) - prec - 1
2130+            temp = Decimal( (self._sign, (0, 1), exp))
2131+            prec = 1
2132+        else:
2133+            temp = Decimal(self)
2134+
2135+        numdigits = len(temp._int)
2136+        if prec == numdigits:
2137+            return temp
2138+
2139+        # See if we need to extend precision
2140+        expdiff = prec - numdigits
2141+        if expdiff > 0:
2142+            tmp = list(temp._int)
2143+            tmp.extend([0] * expdiff)
2144+            ans =  Decimal( (temp._sign, tmp, temp._exp - expdiff))
2145+            return ans
2146+
2147+        #OK, but maybe all the lost digits are 0.
2148+        lostdigits = self._int[expdiff:]
2149+        if lostdigits == (0,) * len(lostdigits):
2150+            ans = Decimal( (temp._sign, temp._int[:prec], temp._exp - expdiff))
2151+            #Rounded, but not Inexact
2152+            context._raise_error(Rounded)
2153+            return ans
2154+
2155+        # Okay, let's round and lose data
2156+
2157+        this_function = getattr(temp, self._pick_rounding_function[rounding])
2158+        #Now we've got the rounding function
2159+
2160+        if prec != context.prec:
2161+            context = context._shallow_copy()
2162+            context.prec = prec
2163+        ans = this_function(prec, expdiff, context)
2164+        context._raise_error(Rounded)
2165+        context._raise_error(Inexact, 'Changed in rounding')
2166+
2167+        return ans
2168+
2169+    _pick_rounding_function = {}
2170+
2171+    def _round_down(self, prec, expdiff, context):
2172+        """Also known as round-towards-0, truncate."""
2173+        return Decimal( (self._sign, self._int[:prec], self._exp - expdiff) )
2174+
2175+    def _round_half_up(self, prec, expdiff, context, tmp = None):
2176+        """Rounds 5 up (away from 0)"""
2177+
2178+        if tmp is None:
2179+            tmp = Decimal( (self._sign,self._int[:prec], self._exp - expdiff))
2180+        if self._int[prec] >= 5:
2181+            tmp = tmp._increment(round=0, context=context)
2182+            if len(tmp._int) > prec:
2183+                return Decimal( (tmp._sign, tmp._int[:-1], tmp._exp + 1))
2184+        return tmp
2185+
2186+    def _round_half_even(self, prec, expdiff, context):
2187+        """Round 5 to even, rest to nearest."""
2188+
2189+        tmp = Decimal( (self._sign, self._int[:prec], self._exp - expdiff))
2190+        half = (self._int[prec] == 5)
2191+        if half:
2192+            for digit in self._int[prec+1:]:
2193+                if digit != 0:
2194+                    half = 0
2195+                    break
2196+        if half:
2197+            if self._int[prec-1] & 1 == 0:
2198+                return tmp
2199+        return self._round_half_up(prec, expdiff, context, tmp)
2200+
2201+    def _round_half_down(self, prec, expdiff, context):
2202+        """Round 5 down"""
2203+
2204+        tmp = Decimal( (self._sign, self._int[:prec], self._exp - expdiff))
2205+        half = (self._int[prec] == 5)
2206+        if half:
2207+            for digit in self._int[prec+1:]:
2208+                if digit != 0:
2209+                    half = 0
2210+                    break
2211+        if half:
2212+            return tmp
2213+        return self._round_half_up(prec, expdiff, context, tmp)
2214+
2215+    def _round_up(self, prec, expdiff, context):
2216+        """Rounds away from 0."""
2217+        tmp = Decimal( (self._sign, self._int[:prec], self._exp - expdiff) )
2218+        for digit in self._int[prec:]:
2219+            if digit != 0:
2220+                tmp = tmp._increment(round=1, context=context)
2221+                if len(tmp._int) > prec:
2222+                    return Decimal( (tmp._sign, tmp._int[:-1], tmp._exp + 1))
2223+                else:
2224+                    return tmp
2225+        return tmp
2226+
2227+    def _round_ceiling(self, prec, expdiff, context):
2228+        """Rounds up (not away from 0 if negative.)"""
2229+        if self._sign:
2230+            return self._round_down(prec, expdiff, context)
2231+        else:
2232+            return self._round_up(prec, expdiff, context)
2233+
2234+    def _round_floor(self, prec, expdiff, context):
2235+        """Rounds down (not towards 0 if negative)"""
2236+        if not self._sign:
2237+            return self._round_down(prec, expdiff, context)
2238+        else:
2239+            return self._round_up(prec, expdiff, context)
2240+
2241+    def __pow__(self, n, modulo = None, context=None):
2242+        """Return self ** n (mod modulo)
2243+
2244+        If modulo is None (default), don't take it mod modulo.
2245+        """
2246+        n = _convert_other(n)
2247+        if n is NotImplemented:
2248+            return n
2249+
2250+        if context is None:
2251+            context = getcontext()
2252+
2253+        if self._is_special or n._is_special or n.adjusted() > 8:
2254+            #Because the spot << doesn't work with really big exponents
2255+            if n._isinfinity() or n.adjusted() > 8:
2256+                return context._raise_error(InvalidOperation, 'x ** INF')
2257+
2258+            ans = self._check_nans(n, context)
2259+            if ans:
2260+                return ans
2261+
2262+        if not n._isinteger():
2263+            return context._raise_error(InvalidOperation, 'x ** (non-integer)')
2264+
2265+        if not self and not n:
2266+            return context._raise_error(InvalidOperation, '0 ** 0')
2267+
2268+        if not n:
2269+            return Decimal(1)
2270+
2271+        if self == Decimal(1):
2272+            return Decimal(1)
2273+
2274+        sign = self._sign and not n._iseven()
2275+        n = int(n)
2276+
2277+        if self._isinfinity():
2278+            if modulo:
2279+                return context._raise_error(InvalidOperation, 'INF % x')
2280+            if n > 0:
2281+                return Infsign[sign]
2282+            return Decimal( (sign, (0,), 0) )
2283+
2284+        #with ludicrously large exponent, just raise an overflow and return inf.
2285+        if not modulo and n > 0 and (self._exp + len(self._int) - 1) * n > context.Emax \
2286+           and self:
2287+
2288+            tmp = Decimal('inf')
2289+            tmp._sign = sign
2290+            context._raise_error(Rounded)
2291+            context._raise_error(Inexact)
2292+            context._raise_error(Overflow, 'Big power', sign)
2293+            return tmp
2294+
2295+        elength = len(str(abs(n)))
2296+        firstprec = context.prec
2297+
2298+        if not modulo and firstprec + elength + 1 > DefaultContext.Emax:
2299+            return context._raise_error(Overflow, 'Too much precision.', sign)
2300+
2301+        mul = Decimal(self)
2302+        val = Decimal(1)
2303+        context = context._shallow_copy()
2304+        context.prec = firstprec + elength + 1
2305+        if n < 0:
2306+            #n is a long now, not Decimal instance
2307+            n = -n
2308+            mul = Decimal(1).__div__(mul, context=context)
2309+
2310+        spot = 1
2311+        while spot <= n:
2312+            spot <<= 1
2313+
2314+        spot >>= 1
2315+        #Spot is the highest power of 2 less than n
2316+        while spot:
2317+            val = val.__mul__(val, context=context)
2318+            if val._isinfinity():
2319+                val = Infsign[sign]
2320+                break
2321+            if spot & n:
2322+                val = val.__mul__(mul, context=context)
2323+            if modulo is not None:
2324+                val = val.__mod__(modulo, context=context)
2325+            spot >>= 1
2326+        context.prec = firstprec
2327+
2328+        if context._rounding_decision == ALWAYS_ROUND:
2329+            return val._fix(context)
2330+        return val
2331+
2332+    def __rpow__(self, other, context=None):
2333+        """Swaps self/other and returns __pow__."""
2334+        other = _convert_other(other)
2335+        if other is NotImplemented:
2336+            return other
2337+        return other.__pow__(self, context=context)
2338+
2339+    def normalize(self, context=None):
2340+        """Normalize- strip trailing 0s, change anything equal to 0 to 0e0"""
2341+
2342+        if self._is_special:
2343+            ans = self._check_nans(context=context)
2344+            if ans:
2345+                return ans
2346+
2347+        dup = self._fix(context)
2348+        if dup._isinfinity():
2349+            return dup
2350+
2351+        if not dup:
2352+            return Decimal( (dup._sign, (0,), 0) )
2353+        end = len(dup._int)
2354+        exp = dup._exp
2355+        while dup._int[end-1] == 0:
2356+            exp += 1
2357+            end -= 1
2358+        return Decimal( (dup._sign, dup._int[:end], exp) )
2359+
2360+
2361+    def quantize(self, exp, rounding=None, context=None, watchexp=1):
2362+        """Quantize self so its exponent is the same as that of exp.
2363+
2364+        Similar to self._rescale(exp._exp) but with error checking.
2365+        """
2366+        if self._is_special or exp._is_special:
2367+            ans = self._check_nans(exp, context)
2368+            if ans:
2369+                return ans
2370+
2371+            if exp._isinfinity() or self._isinfinity():
2372+                if exp._isinfinity() and self._isinfinity():
2373+                    return self  #if both are inf, it is OK
2374+                if context is None:
2375+                    context = getcontext()
2376+                return context._raise_error(InvalidOperation,
2377+                                        'quantize with one INF')
2378+        return self._rescale(exp._exp, rounding, context, watchexp)
2379+
2380+    def same_quantum(self, other):
2381+        """Test whether self and other have the same exponent.
2382+
2383+        same as self._exp == other._exp, except NaN == sNaN
2384+        """
2385+        if self._is_special or other._is_special:
2386+            if self._isnan() or other._isnan():
2387+                return self._isnan() and other._isnan() and True
2388+            if self._isinfinity() or other._isinfinity():
2389+                return self._isinfinity() and other._isinfinity() and True
2390+        return self._exp == other._exp
2391+
2392+    def _rescale(self, exp, rounding=None, context=None, watchexp=1):
2393+        """Rescales so that the exponent is exp.
2394+
2395+        exp = exp to scale to (an integer)
2396+        rounding = rounding version
2397+        watchexp: if set (default) an error is returned if exp is greater
2398+        than Emax or less than Etiny.
2399+        """
2400+        if context is None:
2401+            context = getcontext()
2402+
2403+        if self._is_special:
2404+            if self._isinfinity():
2405+                return context._raise_error(InvalidOperation, 'rescale with an INF')
2406+
2407+            ans = self._check_nans(context=context)
2408+            if ans:
2409+                return ans
2410+
2411+        if watchexp and (context.Emax  < exp or context.Etiny() > exp):
2412+            return context._raise_error(InvalidOperation, 'rescale(a, INF)')
2413+
2414+        if not self:
2415+            ans = Decimal(self)
2416+            ans._int = (0,)
2417+            ans._exp = exp
2418+            return ans
2419+
2420+        diff = self._exp - exp
2421+        digits = len(self._int) + diff
2422+
2423+        if watchexp and digits > context.prec:
2424+            return context._raise_error(InvalidOperation, 'Rescale > prec')
2425+
2426+        tmp = Decimal(self)
2427+        tmp._int = (0,) + tmp._int
2428+        digits += 1
2429+
2430+        if digits < 0:
2431+            tmp._exp = -digits + tmp._exp
2432+            tmp._int = (0,1)
2433+            digits = 1
2434+        tmp = tmp._round(digits, rounding, context=context)
2435+
2436+        if tmp._int[0] == 0 and len(tmp._int) > 1:
2437+            tmp._int = tmp._int[1:]
2438+        tmp._exp = exp
2439+
2440+        tmp_adjusted = tmp.adjusted()
2441+        if tmp and tmp_adjusted < context.Emin:
2442+            context._raise_error(Subnormal)
2443+        elif tmp and tmp_adjusted > context.Emax:
2444+            return context._raise_error(InvalidOperation, 'rescale(a, INF)')
2445+        return tmp
2446+
2447+    def to_integral(self, rounding=None, context=None):
2448+        """Rounds to the nearest integer, without raising inexact, rounded."""
2449+        if self._is_special:
2450+            ans = self._check_nans(context=context)
2451+            if ans:
2452+                return ans
2453+        if self._exp >= 0:
2454+            return self
2455+        if context is None:
2456+            context = getcontext()
2457+        flags = context._ignore_flags(Rounded, Inexact)
2458+        ans = self._rescale(0, rounding, context=context)
2459+        context._regard_flags(flags)
2460+        return ans
2461+
2462+    def sqrt(self, context=None):
2463+        """Return the square root of self.
2464+
2465+        Uses a converging algorithm (Xn+1 = 0.5*(Xn + self / Xn))
2466+        Should quadratically approach the right answer.
2467+        """
2468+        if self._is_special:
2469+            ans = self._check_nans(context=context)
2470+            if ans:
2471+                return ans
2472+
2473+            if self._isinfinity() and self._sign == 0:
2474+                return Decimal(self)
2475+
2476+        if not self:
2477+            #exponent = self._exp / 2, using round_down.
2478+            #if self._exp < 0:
2479+            #    exp = (self._exp+1) // 2
2480+            #else:
2481+            exp = (self._exp) // 2
2482+            if self._sign == 1:
2483+                #sqrt(-0) = -0
2484+                return Decimal( (1, (0,), exp))
2485+            else:
2486+                return Decimal( (0, (0,), exp))
2487+
2488+        if context is None:
2489+            context = getcontext()
2490+
2491+        if self._sign == 1:
2492+            return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
2493+
2494+        tmp = Decimal(self)
2495+
2496+        expadd = tmp._exp // 2
2497+        if tmp._exp & 1:
2498+            tmp._int += (0,)
2499+            tmp._exp = 0
2500+        else:
2501+            tmp._exp = 0
2502+
2503+        context = context._shallow_copy()
2504+        flags = context._ignore_all_flags()
2505+        firstprec = context.prec
2506+        context.prec = 3
2507+        if tmp.adjusted() & 1 == 0:
2508+            ans = Decimal( (0, (8,1,9), tmp.adjusted()  - 2) )
2509+            ans = ans.__add__(tmp.__mul__(Decimal((0, (2,5,9), -2)),
2510+                                          context=context), context=context)
2511+            ans._exp -= 1 + tmp.adjusted() // 2
2512+        else:
2513+            ans = Decimal( (0, (2,5,9), tmp._exp + len(tmp._int)- 3) )
2514+            ans = ans.__add__(tmp.__mul__(Decimal((0, (8,1,9), -3)),
2515+                                          context=context), context=context)
2516+            ans._exp -= 1 + tmp.adjusted()  // 2
2517+
2518+        #ans is now a linear approximation.
2519+
2520+        Emax, Emin = context.Emax, context.Emin
2521+        context.Emax, context.Emin = DefaultContext.Emax, DefaultContext.Emin
2522+
2523+        half = Decimal('0.5')
2524+
2525+        maxp = firstprec + 2
2526+        rounding = context._set_rounding(ROUND_HALF_EVEN)
2527+        while 1:
2528+            context.prec = min(2*context.prec - 2, maxp)
2529+            ans = half.__mul__(ans.__add__(tmp.__div__(ans, context=context),
2530+                                           context=context), context=context)
2531+            if context.prec == maxp:
2532+                break
2533+
2534+        #round to the answer's precision-- the only error can be 1 ulp.
2535+        context.prec = firstprec
2536+        prevexp = ans.adjusted()
2537+        ans = ans._round(context=context)
2538+
2539+        #Now, check if the other last digits are better.
2540+        context.prec = firstprec + 1
2541+        # In case we rounded up another digit and we should actually go lower.
2542+        if prevexp != ans.adjusted():
2543+            ans._int += (0,)
2544+            ans._exp -= 1
2545+
2546+
2547+        lower = ans.__sub__(Decimal((0, (5,), ans._exp-1)), context=context)
2548+        context._set_rounding(ROUND_UP)
2549+        if lower.__mul__(lower, context=context) > (tmp):
2550+            ans = ans.__sub__(Decimal((0, (1,), ans._exp)), context=context)
2551+
2552+        else:
2553+            upper = ans.__add__(Decimal((0, (5,), ans._exp-1)),context=context)
2554+            context._set_rounding(ROUND_DOWN)
2555+            if upper.__mul__(upper, context=context) < tmp:
2556+                ans = ans.__add__(Decimal((0, (1,), ans._exp)),context=context)
2557+
2558+        ans._exp += expadd
2559+
2560+        context.prec = firstprec
2561+        context.rounding = rounding
2562+        ans = ans._fix(context)
2563+
2564+        rounding = context._set_rounding_decision(NEVER_ROUND)
2565+        if not ans.__mul__(ans, context=context) == self:
2566+            # Only rounded/inexact if here.
2567+            context._regard_flags(flags)
2568+            context._raise_error(Rounded)
2569+            context._raise_error(Inexact)
2570+        else:
2571+            #Exact answer, so let's set the exponent right.
2572+            #if self._exp < 0:
2573+            #    exp = (self._exp +1)// 2
2574+            #else:
2575+            exp = self._exp // 2
2576+            context.prec += ans._exp - exp
2577+            ans = ans._rescale(exp, context=context)
2578+            context.prec = firstprec
2579+            context._regard_flags(flags)
2580+        context.Emax, context.Emin = Emax, Emin
2581+
2582+        return ans._fix(context)
2583+
2584+    def max(self, other, context=None):
2585+        """Returns the larger value.
2586+
2587+        like max(self, other) except if one is not a number, returns
2588+        NaN (and signals if one is sNaN).  Also rounds.
2589+        """
2590+        other = _convert_other(other)
2591+        if other is NotImplemented:
2592+            return other
2593+
2594+        if self._is_special or other._is_special:
2595+            # if one operand is a quiet NaN and the other is number, then the
2596+            # number is always returned
2597+            sn = self._isnan()
2598+            on = other._isnan()
2599+            if sn or on:
2600+                if on == 1 and sn != 2:
2601+                    return self
2602+                if sn == 1 and on != 2:
2603+                    return other
2604+                return self._check_nans(other, context)
2605+
2606+        ans = self
2607+        c = self.__cmp__(other)
2608+        if c == 0:
2609+            # if both operands are finite and equal in numerical value
2610+            # then an ordering is applied:
2611+            #
2612+            # if the signs differ then max returns the operand with the
2613+            # positive sign and min returns the operand with the negative sign
2614+            #
2615+            # if the signs are the same then the exponent is used to select
2616+            # the result.
2617+            if self._sign != other._sign:
2618+                if self._sign:
2619+                    ans = other
2620+            elif self._exp < other._exp and not self._sign:
2621+                ans = other
2622+            elif self._exp > other._exp and self._sign:
2623+                ans = other
2624+        elif c == -1:
2625+            ans = other
2626+
2627+        if context is None:
2628+            context = getcontext()
2629+        if context._rounding_decision == ALWAYS_ROUND:
2630+            return ans._fix(context)
2631+        return ans
2632+
2633+    def min(self, other, context=None):
2634+        """Returns the smaller value.
2635+
2636+        like min(self, other) except if one is not a number, returns
2637+        NaN (and signals if one is sNaN).  Also rounds.
2638+        """
2639+        other = _convert_other(other)
2640+        if other is NotImplemented:
2641+            return other
2642+
2643+        if self._is_special or other._is_special:
2644+            # if one operand is a quiet NaN and the other is number, then the
2645+            # number is always returned
2646+            sn = self._isnan()
2647+            on = other._isnan()
2648+            if sn or on:
2649+                if on == 1 and sn != 2:
2650+                    return self
2651+                if sn == 1 and on != 2:
2652+                    return other
2653+                return self._check_nans(other, context)
2654+
2655+        ans = self
2656+        c = self.__cmp__(other)
2657+        if c == 0:
2658+            # if both operands are finite and equal in numerical value
2659+            # then an ordering is applied:
2660+            #
2661+            # if the signs differ then max returns the operand with the
2662+            # positive sign and min returns the operand with the negative sign
2663+            #
2664+            # if the signs are the same then the exponent is used to select
2665+            # the result.
2666+            if self._sign != other._sign:
2667+                if other._sign:
2668+                    ans = other
2669+            elif self._exp > other._exp and not self._sign:
2670+                ans = other
2671+            elif self._exp < other._exp and self._sign:
2672+                ans = other
2673+        elif c == 1:
2674+            ans = other
2675+
2676+        if context is None:
2677+            context = getcontext()
2678+        if context._rounding_decision == ALWAYS_ROUND:
2679+            return ans._fix(context)
2680+        return ans
2681+
2682+    def _isinteger(self):
2683+        """Returns whether self is an integer"""
2684+        if self._exp >= 0:
2685+            return True
2686+        rest = self._int[self._exp:]
2687+        return rest == (0,)*len(rest)
2688+
2689+    def _iseven(self):
2690+        """Returns 1 if self is even.  Assumes self is an integer."""
2691+        if self._exp > 0:
2692+            return 1
2693+        return self._int[-1+self._exp] & 1 == 0
2694+
2695+    def adjusted(self):
2696+        """Return the adjusted exponent of self"""
2697+        try:
2698+            return self._exp + len(self._int) - 1
2699+        #If NaN or Infinity, self._exp is string
2700+        except TypeError:
2701+            return 0
2702+
2703+    # support for pickling, copy, and deepcopy
2704+    def __reduce__(self):
2705+        return (self.__class__, (str(self),))
2706+
2707+    def __copy__(self):
2708+        if type(self) == Decimal:
2709+            return self     # I'm immutable; therefore I am my own clone
2710+        return self.__class__(str(self))
2711+
2712+    def __deepcopy__(self, memo):
2713+        if type(self) == Decimal:
2714+            return self     # My components are also immutable
2715+        return self.__class__(str(self))
2716+
2717+##### Context class ###########################################
2718+
2719+
2720+# get rounding method function:
2721+rounding_functions = [name for name in Decimal.__dict__.keys() if name.startswith('_round_')]
2722+for name in rounding_functions:
2723+    #name is like _round_half_even, goes to the global ROUND_HALF_EVEN value.
2724+    globalname = name[1:].upper()
2725+    val = globals()[globalname]
2726+    Decimal._pick_rounding_function[val] = name
2727+
2728+del name, val, globalname, rounding_functions
2729+
2730+class Context(object):
2731+    """Contains the context for a Decimal instance.
2732+
2733+    Contains:
2734+    prec - precision (for use in rounding, division, square roots..)
2735+    rounding - rounding type. (how you round)
2736+    _rounding_decision - ALWAYS_ROUND, NEVER_ROUND -- do you round?
2737+    traps - If traps[exception] = 1, then the exception is
2738+                    raised when it is caused.  Otherwise, a value is
2739+                    substituted in.
2740+    flags  - When an exception is caused, flags[exception] is incremented.
2741+             (Whether or not the trap_enabler is set)
2742+             Should be reset by user of Decimal instance.
2743+    Emin -   Minimum exponent
2744+    Emax -   Maximum exponent
2745+    capitals -      If 1, 1*10^1 is printed as 1E+1.
2746+                    If 0, printed as 1e1
2747+    _clamp - If 1, change exponents if too high (Default 0)
2748+    """
2749+
2750+    def __init__(self, prec=None, rounding=None,
2751+                 traps=None, flags=None,
2752+                 _rounding_decision=None,
2753+                 Emin=None, Emax=None,
2754+                 capitals=None, _clamp=0,
2755+                 _ignored_flags=None):
2756+        if flags is None:
2757+            flags = []
2758+        if _ignored_flags is None:
2759+            _ignored_flags = []
2760+        if not isinstance(flags, dict):
2761+            flags = dict([(s,s in flags) for s in _signals])
2762+            del s
2763+        if traps is not None and not isinstance(traps, dict):
2764+            traps = dict([(s,s in traps) for s in _signals])
2765+            del s
2766+        for name, val in locals().items():
2767+            if val is None:
2768+                setattr(self, name, copy.copy(getattr(DefaultContext, name)))
2769+            else:
2770+                setattr(self, name, val)
2771+        del self.self
2772+
2773+    def __repr__(self):
2774+        """Show the current context."""
2775+        s = []
2776+        s.append('Context(prec=%(prec)d, rounding=%(rounding)s, Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d' % vars(self))
2777+        s.append('flags=[' + ', '.join([f.__name__ for f, v in self.flags.items() if v]) + ']')
2778+        s.append('traps=[' + ', '.join([t.__name__ for t, v in self.traps.items() if v]) + ']')
2779+        return ', '.join(s) + ')'
2780+
2781+    def clear_flags(self):
2782+        """Reset all flags to zero"""
2783+        for flag in self.flags:
2784+            self.flags[flag] = 0
2785+
2786+    def _shallow_copy(self):
2787+        """Returns a shallow copy from self."""
2788+        nc = Context(self.prec, self.rounding, self.traps, self.flags,
2789+                         self._rounding_decision, self.Emin, self.Emax,
2790+                         self.capitals, self._clamp, self._ignored_flags)
2791+        return nc
2792+
2793+    def copy(self):
2794+        """Returns a deep copy from self."""
2795+        nc = Context(self.prec, self.rounding, self.traps.copy(), self.flags.copy(),
2796+                         self._rounding_decision, self.Emin, self.Emax,
2797+                         self.capitals, self._clamp, self._ignored_flags)
2798+        return nc
2799+    __copy__ = copy
2800+
2801+    def _raise_error(self, condition, explanation = None, *args):
2802+        """Handles an error
2803+
2804+        If the flag is in _ignored_flags, returns the default response.
2805+        Otherwise, it increments the flag, then, if the corresponding
2806+        trap_enabler is set, it reaises the exception.  Otherwise, it returns
2807+        the default value after incrementing the flag.
2808+        """
2809+        error = _condition_map.get(condition, condition)
2810+        if error in self._ignored_flags:
2811+            #Don't touch the flag
2812+            return error().handle(self, *args)
2813+
2814+        self.flags[error] += 1
2815+        if not self.traps[error]:
2816+            #The errors define how to handle themselves.
2817+            return condition().handle(self, *args)
2818+
2819+        # Errors should only be risked on copies of the context
2820+        #self._ignored_flags = []
2821+        raise error, explanation
2822+
2823+    def _ignore_all_flags(self):
2824+        """Ignore all flags, if they are raised"""
2825+        return self._ignore_flags(*_signals)
2826+
2827+    def _ignore_flags(self, *flags):
2828+        """Ignore the flags, if they are raised"""
2829+        # Do not mutate-- This way, copies of a context leave the original
2830+        # alone.
2831+        self._ignored_flags = (self._ignored_flags + list(flags))
2832+        return list(flags)
2833+
2834+    def _regard_flags(self, *flags):
2835+        """Stop ignoring the flags, if they are raised"""
2836+        if flags and isinstance(flags[0], (tuple,list)):
2837+            flags = flags[0]
2838+        for flag in flags:
2839+            self._ignored_flags.remove(flag)
2840+
2841+    def __hash__(self):
2842+        """A Context cannot be hashed."""
2843+        # We inherit object.__hash__, so we must deny this explicitly
2844+        raise TypeError, "Cannot hash a Context."
2845+
2846+    def Etiny(self):
2847+        """Returns Etiny (= Emin - prec + 1)"""
2848+        return int(self.Emin - self.prec + 1)
2849+
2850+    def Etop(self):
2851+        """Returns maximum exponent (= Emax - prec + 1)"""
2852+        return int(self.Emax - self.prec + 1)
2853+
2854+    def _set_rounding_decision(self, type):
2855+        """Sets the rounding decision.
2856+
2857+        Sets the rounding decision, and returns the current (previous)
2858+        rounding decision.  Often used like:
2859+
2860+        context = context._shallow_copy()
2861+        # That so you don't change the calling context
2862+        # if an error occurs in the middle (say DivisionImpossible is raised).
2863+
2864+        rounding = context._set_rounding_decision(NEVER_ROUND)
2865+        instance = instance / Decimal(2)
2866+        context._set_rounding_decision(rounding)
2867+
2868+        This will make it not round for that operation.
2869+        """
2870+
2871+        rounding = self._rounding_decision
2872+        self._rounding_decision = type
2873+        return rounding
2874+
2875+    def _set_rounding(self, type):
2876+        """Sets the rounding type.
2877+
2878+        Sets the rounding type, and returns the current (previous)
2879+        rounding type.  Often used like:
2880+
2881+        context = context.copy()
2882+        # so you don't change the calling context
2883+        # if an error occurs in the middle.
2884+        rounding = context._set_rounding(ROUND_UP)
2885+        val = self.__sub__(other, context=context)
2886+        context._set_rounding(rounding)
2887+
2888+        This will make it round up for that operation.
2889+        """
2890+        rounding = self.rounding
2891+        self.rounding= type
2892+        return rounding
2893+
2894+    def create_decimal(self, num='0'):
2895+        """Creates a new Decimal instance but using self as context."""
2896+        d = Decimal(num, context=self)
2897+        return d._fix(self)
2898+
2899+    #Methods
2900+    def abs(self, a):
2901+        """Returns the absolute value of the operand.
2902+
2903+        If the operand is negative, the result is the same as using the minus
2904+        operation on the operand. Otherwise, the result is the same as using
2905+        the plus operation on the operand.
2906+
2907+        >>> ExtendedContext.abs(Decimal('2.1'))
2908+        Decimal("2.1")
2909+        >>> ExtendedContext.abs(Decimal('-100'))
2910+        Decimal("100")
2911+        >>> ExtendedContext.abs(Decimal('101.5'))
2912+        Decimal("101.5")
2913+        >>> ExtendedContext.abs(Decimal('-101.5'))
2914+        Decimal("101.5")
2915+        """
2916+        return a.__abs__(context=self)
2917+
2918+    def add(self, a, b):
2919+        """Return the sum of the two operands.
2920+
2921+        >>> ExtendedContext.add(Decimal('12'), Decimal('7.00'))
2922+        Decimal("19.00")
2923+        >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4'))
2924+        Decimal("1.02E+4")
2925+        """
2926+        return a.__add__(b, context=self)
2927+
2928+    def _apply(self, a):
2929+        return str(a._fix(self))
2930+
2931+    def compare(self, a, b):
2932+        """Compares values numerically.
2933+
2934+        If the signs of the operands differ, a value representing each operand
2935+        ('-1' if the operand is less than zero, '0' if the operand is zero or
2936+        negative zero, or '1' if the operand is greater than zero) is used in
2937+        place of that operand for the comparison instead of the actual
2938+        operand.
2939+
2940+        The comparison is then effected by subtracting the second operand from
2941+        the first and then returning a value according to the result of the
2942+        subtraction: '-1' if the result is less than zero, '0' if the result is
2943+        zero or negative zero, or '1' if the result is greater than zero.
2944+
2945+        >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3'))
2946+        Decimal("-1")
2947+        >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1'))
2948+        Decimal("0")
2949+        >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10'))
2950+        Decimal("0")
2951+        >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1'))
2952+        Decimal("1")
2953+        >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3'))
2954+        Decimal("1")
2955+        >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1'))
2956+        Decimal("-1")
2957+        """
2958+        return a.compare(b, context=self)
2959+
2960+    def divide(self, a, b):
2961+        """Decimal division in a specified context.
2962+
2963+        >>> ExtendedContext.divide(Decimal('1'), Decimal('3'))
2964+        Decimal("0.333333333")
2965+        >>> ExtendedContext.divide(Decimal('2'), Decimal('3'))
2966+        Decimal("0.666666667")
2967+        >>> ExtendedContext.divide(Decimal('5'), Decimal('2'))
2968+        Decimal("2.5")
2969+        >>> ExtendedContext.divide(Decimal('1'), Decimal('10'))
2970+        Decimal("0.1")
2971+        >>> ExtendedContext.divide(Decimal('12'), Decimal('12'))
2972+        Decimal("1")
2973+        >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2'))
2974+        Decimal("4.00")
2975+        >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0'))
2976+        Decimal("1.20")
2977+        >>> ExtendedContext.divide(Decimal('1000'), Decimal('100'))
2978+        Decimal("10")
2979+        >>> ExtendedContext.divide(Decimal('1000'), Decimal('1'))
2980+        Decimal("1000")
2981+        >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2'))
2982+        Decimal("1.20E+6")
2983+        """
2984+        return a.__div__(b, context=self)
2985+
2986+    def divide_int(self, a, b):
2987+        """Divides two numbers and returns the integer part of the result.
2988+
2989+        >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3'))
2990+        Decimal("0")
2991+        >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3'))
2992+        Decimal("3")
2993+        >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3'))
2994+        Decimal("3")
2995+        """
2996+        return a.__floordiv__(b, context=self)
2997+
2998+    def divmod(self, a, b):
2999+        return a.__divmod__(b, context=self)
3000+
3001+    def max(self, a,b):
3002+        """max compares two values numerically and returns the maximum.
3003+
3004+        If either operand is a NaN then the general rules apply.
3005+        Otherwise, the operands are compared as as though by the compare
3006+        operation. If they are numerically equal then the left-hand operand
3007+        is chosen as the result. Otherwise the maximum (closer to positive
3008+        infinity) of the two operands is chosen as the result.
3009+
3010+        >>> ExtendedContext.max(Decimal('3'), Decimal('2'))
3011+        Decimal("3")
3012+        >>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
3013+        Decimal("3")
3014+        >>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
3015+        Decimal("1")
3016+        >>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
3017+        Decimal("7")
3018+        """
3019+        return a.max(b, context=self)
3020+
3021+    def min(self, a,b):
3022+        """min compares two values numerically and returns the minimum.
3023+
3024+        If either operand is a NaN then the general rules apply.
3025+        Otherwise, the operands are compared as as though by the compare
3026+        operation. If they are numerically equal then the left-hand operand
3027+        is chosen as the result. Otherwise the minimum (closer to negative
3028+        infinity) of the two operands is chosen as the result.
3029+
3030+        >>> ExtendedContext.min(Decimal('3'), Decimal('2'))
3031+        Decimal("2")
3032+        >>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
3033+        Decimal("-10")
3034+        >>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
3035+        Decimal("1.0")
3036+        >>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
3037+        Decimal("7")
3038+        """
3039+        return a.min(b, context=self)
3040+
3041+    def minus(self, a):
3042+        """Minus corresponds to unary prefix minus in Python.
3043+
3044+        The operation is evaluated using the same rules as subtract; the
3045+        operation minus(a) is calculated as subtract('0', a) where the '0'
3046+        has the same exponent as the operand.
3047+
3048+        >>> ExtendedContext.minus(Decimal('1.3'))
3049+        Decimal("-1.3")
3050+        >>> ExtendedContext.minus(Decimal('-1.3'))
3051+        Decimal("1.3")
3052+        """
3053+        return a.__neg__(context=self)
3054+
3055+    def multiply(self, a, b):
3056+        """multiply multiplies two operands.
3057+
3058+        If either operand is a special value then the general rules apply.
3059+        Otherwise, the operands are multiplied together ('long multiplication'),
3060+        resulting in a number which may be as long as the sum of the lengths
3061+        of the two operands.
3062+
3063+        >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3'))
3064+        Decimal("3.60")
3065+        >>> ExtendedContext.multiply(Decimal('7'), Decimal('3'))
3066+        Decimal("21")
3067+        >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8'))
3068+        Decimal("0.72")
3069+        >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0'))
3070+        Decimal("-0.0")
3071+        >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321'))
3072+        Decimal("4.28135971E+11")
3073+        """
3074+        return a.__mul__(b, context=self)
3075+
3076+    def normalize(self, a):
3077+        """normalize reduces an operand to its simplest form.
3078+
3079+        Essentially a plus operation with all trailing zeros removed from the
3080+        result.
3081+
3082+        >>> ExtendedContext.normalize(Decimal('2.1'))
3083+        Decimal("2.1")
3084+        >>> ExtendedContext.normalize(Decimal('-2.0'))
3085+        Decimal("-2")
3086+        >>> ExtendedContext.normalize(Decimal('1.200'))
3087+        Decimal("1.2")
3088+        >>> ExtendedContext.normalize(Decimal('-120'))
3089+        Decimal("-1.2E+2")
3090+        >>> ExtendedContext.normalize(Decimal('120.00'))
3091+        Decimal("1.2E+2")
3092+        >>> ExtendedContext.normalize(Decimal('0.00'))
3093+        Decimal("0")
3094+        """
3095+        return a.normalize(context=self)
3096+
3097+    def plus(self, a):
3098+        """Plus corresponds to unary prefix plus in Python.
3099+
3100+        The operation is evaluated using the same rules as add; the
3101+        operation plus(a) is calculated as add('0', a) where the '0'
3102+        has the same exponent as the operand.
3103+
3104+        >>> ExtendedContext.plus(Decimal('1.3'))
3105+        Decimal("1.3")
3106+        >>> ExtendedContext.plus(Decimal('-1.3'))
3107+        Decimal("-1.3")
3108+        """
3109+        return a.__pos__(context=self)
3110+
3111+    def power(self, a, b, modulo=None):
3112+        """Raises a to the power of b, to modulo if given.
3113+
3114+        The right-hand operand must be a whole number whose integer part (after
3115+        any exponent has been applied) has no more than 9 digits and whose
3116+        fractional part (if any) is all zeros before any rounding. The operand
3117+        may be positive, negative, or zero; if negative, the absolute value of
3118+        the power is used, and the left-hand operand is inverted (divided into
3119+        1) before use.
3120+
3121+        If the increased precision needed for the intermediate calculations
3122+        exceeds the capabilities of the implementation then an Invalid operation
3123+        condition is raised.
3124+
3125+        If, when raising to a negative power, an underflow occurs during the
3126+        division into 1, the operation is not halted at that point but
3127+        continues.
3128+
3129+        >>> ExtendedContext.power(Decimal('2'), Decimal('3'))
3130+        Decimal("8")
3131+        >>> ExtendedContext.power(Decimal('2'), Decimal('-3'))
3132+        Decimal("0.125")
3133+        >>> ExtendedContext.power(Decimal('1.7'), Decimal('8'))
3134+        Decimal("69.7575744")
3135+        >>> ExtendedContext.power(Decimal('Infinity'), Decimal('-2'))
3136+        Decimal("0")
3137+        >>> ExtendedContext.power(Decimal('Infinity'), Decimal('-1'))
3138+        Decimal("0")
3139+        >>> ExtendedContext.power(Decimal('Infinity'), Decimal('0'))
3140+        Decimal("1")
3141+        >>> ExtendedContext.power(Decimal('Infinity'), Decimal('1'))
3142+        Decimal("Infinity")
3143+        >>> ExtendedContext.power(Decimal('Infinity'), Decimal('2'))
3144+        Decimal("Infinity")
3145+        >>> ExtendedContext.power(Decimal('-Infinity'), Decimal('-2'))
3146+        Decimal("0")
3147+        >>> ExtendedContext.power(Decimal('-Infinity'), Decimal('-1'))
3148+        Decimal("-0")
3149+        >>> ExtendedContext.power(Decimal('-Infinity'), Decimal('0'))
3150+        Decimal("1")
3151+        >>> ExtendedContext.power(Decimal('-Infinity'), Decimal('1'))
3152+        Decimal("-Infinity")
3153+        >>> ExtendedContext.power(Decimal('-Infinity'), Decimal('2'))
3154+        Decimal("Infinity")
3155+        >>> ExtendedContext.power(Decimal('0'), Decimal('0'))
3156+        Decimal("NaN")
3157+        """
3158+        return a.__pow__(b, modulo, context=self)
3159+
3160+    def quantize(self, a, b):
3161+        """Returns a value equal to 'a' (rounded) and having the exponent of 'b'.
3162+
3163+        The coefficient of the result is derived from that of the left-hand
3164+        operand. It may be rounded using the current rounding setting (if the
3165+        exponent is being increased), multiplied by a positive power of ten (if
3166+        the exponent is being decreased), or is unchanged (if the exponent is
3167+        already equal to that of the right-hand operand).
3168+
3169+        Unlike other operations, if the length of the coefficient after the
3170+        quantize operation would be greater than precision then an Invalid
3171+        operation condition is raised. This guarantees that, unless there is an
3172+        error condition, the exponent of the result of a quantize is always
3173+        equal to that of the right-hand operand.
3174+
3175+        Also unlike other operations, quantize will never raise Underflow, even
3176+        if the result is subnormal and inexact.
3177+
3178+        >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001'))
3179+        Decimal("2.170")
3180+        >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01'))
3181+        Decimal("2.17")
3182+        >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1'))
3183+        Decimal("2.2")
3184+        >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0'))
3185+        Decimal("2")
3186+        >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1'))
3187+        Decimal("0E+1")
3188+        >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity'))
3189+        Decimal("-Infinity")
3190+        >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity'))
3191+        Decimal("NaN")
3192+        >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1'))
3193+        Decimal("-0")
3194+        >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5'))
3195+        Decimal("-0E+5")
3196+        >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2'))
3197+        Decimal("NaN")
3198+        >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2'))
3199+        Decimal("NaN")
3200+        >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1'))
3201+        Decimal("217.0")
3202+        >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0'))
3203+        Decimal("217")
3204+        >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1'))
3205+        Decimal("2.2E+2")
3206+        >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2'))
3207+        Decimal("2E+2")
3208+        """
3209+        return a.quantize(b, context=self)
3210+
3211+    def remainder(self, a, b):
3212+        """Returns the remainder from integer division.
3213+
3214+        The result is the residue of the dividend after the operation of
3215+        calculating integer division as described for divide-integer, rounded to
3216+        precision digits if necessary. The sign of the result, if non-zero, is
3217+        the same as that of the original dividend.
3218+
3219+        This operation will fail under the same conditions as integer division
3220+        (that is, if integer division on the same two operands would fail, the
3221+        remainder cannot be calculated).
3222+
3223+        >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3'))
3224+        Decimal("2.1")
3225+        >>> ExtendedContext.remainder(Decimal('10'), Decimal('3'))
3226+        Decimal("1")
3227+        >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3'))
3228+        Decimal("-1")
3229+        >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1'))
3230+        Decimal("0.2")
3231+        >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3'))
3232+        Decimal("0.1")
3233+        >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3'))
3234+        Decimal("1.0")
3235+        """
3236+        return a.__mod__(b, context=self)
3237+
3238+    def remainder_near(self, a, b):
3239+        """Returns to be "a - b * n", where n is the integer nearest the exact
3240+        value of "x / b" (if two integers are equally near then the even one
3241+        is chosen). If the result is equal to 0 then its sign will be the
3242+        sign of a.
3243+
3244+        This operation will fail under the same conditions as integer division
3245+        (that is, if integer division on the same two operands would fail, the
3246+        remainder cannot be calculated).
3247+
3248+        >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3'))
3249+        Decimal("-0.9")
3250+        >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
3251+        Decimal("-2")
3252+        >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3'))
3253+        Decimal("1")
3254+        >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3'))
3255+        Decimal("-1")
3256+        >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1'))
3257+        Decimal("0.2")
3258+        >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
3259+        Decimal("0.1")
3260+        >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3'))
3261+        Decimal("-0.3")
3262+        """
3263+        return a.remainder_near(b, context=self)
3264+
3265+    def same_quantum(self, a, b):
3266+        """Returns True if the two operands have the same exponent.
3267+
3268+        The result is never affected by either the sign or the coefficient of
3269+        either operand.
3270+
3271+        >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
3272+        False
3273+        >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
3274+        True
3275+        >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
3276+        False
3277+        >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
3278+        True
3279+        """
3280+        return a.same_quantum(b)
3281+
3282+    def sqrt(self, a):
3283+        """Returns the square root of a non-negative number to context precision.
3284+
3285+        If the result must be inexact, it is rounded using the round-half-even
3286+        algorithm.
3287+
3288+        >>> ExtendedContext.sqrt(Decimal('0'))
3289+        Decimal("0")
3290+        >>> ExtendedContext.sqrt(Decimal('-0'))
3291+        Decimal("-0")
3292+        >>> ExtendedContext.sqrt(Decimal('0.39'))
3293+        Decimal("0.624499800")
3294+        >>> ExtendedContext.sqrt(Decimal('100'))
3295+        Decimal("10")
3296+        >>> ExtendedContext.sqrt(Decimal('1'))
3297+        Decimal("1")
3298+        >>> ExtendedContext.sqrt(Decimal('1.0'))
3299+        Decimal("1.0")
3300+        >>> ExtendedContext.sqrt(Decimal('1.00'))
3301+        Decimal("1.0")
3302+        >>> ExtendedContext.sqrt(Decimal('7'))
3303+        Decimal("2.64575131")
3304+        >>> ExtendedContext.sqrt(Decimal('10'))
3305+        Decimal("3.16227766")
3306+        >>> ExtendedContext.prec
3307+        9
3308+        """
3309+        return a.sqrt(context=self)
3310+
3311+    def subtract(self, a, b):
3312+        """Return the sum of the two operands.
3313+
3314+        >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07'))
3315+        Decimal("0.23")
3316+        >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30'))
3317+        Decimal("0.00")
3318+        >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07'))
3319+        Decimal("-0.77")
3320+        """
3321+        return a.__sub__(b, context=self)
3322+
3323+    def to_eng_string(self, a):
3324+        """Converts a number to a string, using scientific notation.
3325+
3326+        The operation is not affected by the context.
3327+        """
3328+        return a.to_eng_string(context=self)
3329+
3330+    def to_sci_string(self, a):
3331+        """Converts a number to a string, using scientific notation.
3332+
3333+        The operation is not affected by the context.
3334+        """
3335+        return a.__str__(context=self)
3336+
3337+    def to_integral(self, a):
3338+        """Rounds to an integer.
3339+
3340+        When the operand has a negative exponent, the result is the same
3341+        as using the quantize() operation using the given operand as the
3342+        left-hand-operand, 1E+0 as the right-hand-operand, and the precision
3343+        of the operand as the precision setting, except that no flags will
3344+        be set. The rounding mode is taken from the context.
3345+
3346+        >>> ExtendedContext.to_integral(Decimal('2.1'))
3347+        Decimal("2")
3348+        >>> ExtendedContext.to_integral(Decimal('100'))
3349+        Decimal("100")
3350+        >>> ExtendedContext.to_integral(Decimal('100.0'))
3351+        Decimal("100")
3352+        >>> ExtendedContext.to_integral(Decimal('101.5'))
3353+        Decimal("102")
3354+        >>> ExtendedContext.to_integral(Decimal('-101.5'))
3355+        Decimal("-102")
3356+        >>> ExtendedContext.to_integral(Decimal('10E+5'))
3357+        Decimal("1.0E+6")
3358+        >>> ExtendedContext.to_integral(Decimal('7.89E+77'))
3359+        Decimal("7.89E+77")
3360+        >>> ExtendedContext.to_integral(Decimal('-Inf'))
3361+        Decimal("-Infinity")
3362+        """
3363+        return a.to_integral(context=self)
3364+
3365+class _WorkRep(object):
3366+    __slots__ = ('sign','int','exp')
3367+    # sign: 0 or 1
3368+    # int:  int or long
3369+    # exp:  None, int, or string
3370+
3371+    def __init__(self, value=None):
3372+        if value is None:
3373+            self.sign = None
3374+            self.int = 0
3375+            self.exp = None
3376+        elif isinstance(value, Decimal):
3377+            self.sign = value._sign
3378+            cum = 0
3379+            for digit  in value._int:
3380+                cum = cum * 10 + digit
3381+            self.int = cum
3382+            self.exp = value._exp
3383+        else:
3384+            # assert isinstance(value, tuple)
3385+            self.sign = value[0]
3386+            self.int = value[1]
3387+            self.exp = value[2]
3388+
3389+    def __repr__(self):
3390+        return "(%r, %r, %r)" % (self.sign, self.int, self.exp)
3391+
3392+    __str__ = __repr__
3393+
3394+
3395+
3396+def _normalize(op1, op2, shouldround = 0, prec = 0):
3397+    """Normalizes op1, op2 to have the same exp and length of coefficient.
3398+
3399+    Done during addition.
3400+    """
3401+    # Yes, the exponent is a long, but the difference between exponents
3402+    # must be an int-- otherwise you'd get a big memory problem.
3403+    numdigits = int(op1.exp - op2.exp)
3404+    if numdigits < 0:
3405+        numdigits = -numdigits
3406+        tmp = op2
3407+        other = op1
3408+    else:
3409+        tmp = op1
3410+        other = op2
3411+
3412+
3413+    if shouldround and numdigits > prec + 1:
3414+        # Big difference in exponents - check the adjusted exponents
3415+        tmp_len = len(str(tmp.int))
3416+        other_len = len(str(other.int))
3417+        if numdigits > (other_len + prec + 1 - tmp_len):
3418+            # If the difference in adjusted exps is > prec+1, we know
3419+            # other is insignificant, so might as well put a 1 after the precision.
3420+            # (since this is only for addition.)  Also stops use of massive longs.
3421+
3422+            extend = prec + 2 - tmp_len
3423+            if extend <= 0:
3424+                extend = 1
3425+            tmp.int *= 10 ** extend
3426+            tmp.exp -= extend
3427+            other.int = 1
3428+            other.exp = tmp.exp
3429+            return op1, op2
3430+
3431+    tmp.int *= 10 ** numdigits
3432+    tmp.exp -= numdigits
3433+    return op1, op2
3434+
3435+def _adjust_coefficients(op1, op2):
3436+    """Adjust op1, op2 so that op2.int * 10 > op1.int >= op2.int.
3437+
3438+    Returns the adjusted op1, op2 as well as the change in op1.exp-op2.exp.
3439+
3440+    Used on _WorkRep instances during division.
3441+    """
3442+    adjust = 0
3443+    #If op1 is smaller, make it larger
3444+    while op2.int > op1.int:
3445+        op1.int *= 10
3446+        op1.exp -= 1
3447+        adjust += 1
3448+
3449+    #If op2 is too small, make it larger
3450+    while op1.int >= (10 * op2.int):
3451+        op2.int *= 10
3452+        op2.exp -= 1
3453+        adjust -= 1
3454+
3455+    return op1, op2, adjust
3456+
3457+##### Helper Functions ########################################
3458+
3459+def _convert_other(other):
3460+    """Convert other to Decimal.
3461+
3462+    Verifies that it's ok to use in an implicit construction.
3463+    """
3464+    if isinstance(other, Decimal):
3465+        return other
3466+    if isinstance(other, (int, long)):
3467+        return Decimal(other)
3468+    return NotImplemented
3469+
3470+_infinity_map = {
3471+    'inf' : 1,
3472+    'infinity' : 1,
3473+    '+inf' : 1,
3474+    '+infinity' : 1,
3475+    '-inf' : -1,
3476+    '-infinity' : -1
3477+}
3478+
3479+def _isinfinity(num):
3480+    """Determines whether a string or float is infinity.
3481+
3482+    +1 for negative infinity; 0 for finite ; +1 for positive infinity
3483+    """
3484+    num = str(num).lower()
3485+    return _infinity_map.get(num, 0)
3486+
3487+def _isnan(num):
3488+    """Determines whether a string or float is NaN
3489+
3490+    (1, sign, diagnostic info as string) => NaN
3491+    (2, sign, diagnostic info as string) => sNaN
3492+    0 => not a NaN
3493+    """
3494+    num = str(num).lower()
3495+    if not num:
3496+        return 0
3497+
3498+    #get the sign, get rid of trailing [+-]
3499+    sign = 0
3500+    if num[0] == '+':
3501+        num = num[1:]
3502+    elif num[0] == '-':  #elif avoids '+-nan'
3503+        num = num[1:]
3504+        sign = 1
3505+
3506+    if num.startswith('nan'):
3507+        if len(num) > 3 and not num[3:].isdigit(): #diagnostic info
3508+            return 0
3509+        return (1, sign, num[3:].lstrip('0'))
3510+    if num.startswith('snan'):
3511+        if len(num) > 4 and not num[4:].isdigit():
3512+            return 0
3513+        return (2, sign, num[4:].lstrip('0'))
3514+    return 0
3515+
3516+
3517+##### Setup Specific Contexts ################################
3518+
3519+# The default context prototype used by Context()
3520+# Is mutable, so that new contexts can have different default values
3521+
3522+DefaultContext = Context(
3523+        prec=28, rounding=ROUND_HALF_EVEN,
3524+        traps=[DivisionByZero, Overflow, InvalidOperation],
3525+        flags=[],
3526+        _rounding_decision=ALWAYS_ROUND,
3527+        Emax=999999999,
3528+        Emin=-999999999,
3529+        capitals=1
3530+)
3531+
3532+# Pre-made alternate contexts offered by the specification
3533+# Don't change these; the user should be able to select these
3534+# contexts and be able to reproduce results from other implementations
3535+# of the spec.
3536+
3537+BasicContext = Context(
3538+        prec=9, rounding=ROUND_HALF_UP,
3539+        traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow],
3540+        flags=[],
3541+)
3542+
3543+ExtendedContext = Context(
3544+        prec=9, rounding=ROUND_HALF_EVEN,
3545+        traps=[],
3546+        flags=[],
3547+)
3548+
3549+
3550+##### Useful Constants (internal use only) ####################
3551+
3552+#Reusable defaults
3553+Inf = Decimal('Inf')
3554+negInf = Decimal('-Inf')
3555+
3556+#Infsign[sign] is infinity w/ that sign
3557+Infsign = (Inf, negInf)
3558+
3559+NaN = Decimal('NaN')
3560+
3561+
3562+##### crud for parsing strings #################################
3563+import re
3564+
3565+# There's an optional sign at the start, and an optional exponent
3566+# at the end.  The exponent has an optional sign and at least one
3567+# digit.  In between, must have either at least one digit followed
3568+# by an optional fraction, or a decimal point followed by at least
3569+# one digit.  Yuck.
3570+
3571+_parser = re.compile(r"""
3572+#    \s*
3573+    (?P<sign>[-+])?
3574+    (
3575+        (?P<int>\d+) (\. (?P<frac>\d*))?
3576+    |
3577+        \. (?P<onlyfrac>\d+)
3578+    )
3579+    ([eE](?P<exp>[-+]? \d+))?
3580+#    \s*
3581+    $
3582+""", re.VERBOSE).match #Uncomment the \s* to allow leading or trailing spaces.
3583+
3584+del re
3585+
3586+# return sign, n, p s.t. float string value == -1**sign * n * 10**p exactly
3587+
3588+def _string2exact(s):
3589+    m = _parser(s)
3590+    if m is None:
3591+        raise ValueError("invalid literal for Decimal: %r" % s)
3592+
3593+    if m.group('sign') == "-":
3594+        sign = 1
3595+    else:
3596+        sign = 0
3597+
3598+    exp = m.group('exp')
3599+    if exp is None:
3600+        exp = 0
3601+    else:
3602+        exp = int(exp)
3603+
3604+    intpart = m.group('int')
3605+    if intpart is None:
3606+        intpart = ""
3607+        fracpart = m.group('onlyfrac')
3608+    else:
3609+        fracpart = m.group('frac')
3610+        if fracpart is None:
3611+            fracpart = ""
3612+
3613+    exp -= len(fracpart)
3614+
3615+    mantissa = intpart + fracpart
3616+    tmp = map(int, mantissa)
3617+    backup = tmp
3618+    while tmp and tmp[0] == 0:
3619+        del tmp[0]
3620+
3621+    # It's a zero
3622+    if not tmp:
3623+        if backup:
3624+            return (sign, tuple(backup), exp)
3625+        return (sign, (0,), exp)
3626+    mantissa = tuple(tmp)
3627+
3628+    return (sign, mantissa, exp)
3629+
3630+
3631+if __name__ == '__main__':
3632+    import doctest, sys
3633+    doctest.testmod(sys.modules[__name__])
3634Index: tests/modeltests/invalid_models/models.py
3635===================================================================
3636--- tests/modeltests/invalid_models/models.py   (revision 4439)
3637+++ tests/modeltests/invalid_models/models.py   (working copy)
3638@@ -8,7 +8,7 @@
3639 
3640 class FieldErrors(models.Model):
3641     charfield = models.CharField()
3642-    floatfield = models.FloatField()
3643+    decimalfield = models.DecimalField()
3644     filefield = models.FileField()
3645     prepopulate = models.CharField(maxlength=10, prepopulate_from='bad')
3646     choices = models.CharField(maxlength=10, choices='bad')
3647@@ -98,8 +98,8 @@
3648     m2m_4 = models.ManyToManyField('self', symmetrical=False)
3649 
3650 model_errors = """invalid_models.fielderrors: "charfield": CharFields require a "maxlength" attribute.
3651-invalid_models.fielderrors: "floatfield": FloatFields require a "decimal_places" attribute.
3652-invalid_models.fielderrors: "floatfield": FloatFields require a "max_digits" attribute.
3653+invalid_models.fielderrors: "decimalfield": DecimalFields require a "decimal_places" attribute.
3654+invalid_models.fielderrors: "decimalfield": DecimalFields require a "max_digits" attribute.
3655 invalid_models.fielderrors: "filefield": FileFields require an "upload_to" attribute.
3656 invalid_models.fielderrors: "prepopulate": prepopulate_from should be a list or tuple.
3657 invalid_models.fielderrors: "choices": "choices" should be iterable (e.g., a tuple or list).
3658Index: tests/regressiontests/forms/tests.py
3659===================================================================
3660--- tests/regressiontests/forms/tests.py        (revision 4439)
3661+++ tests/regressiontests/forms/tests.py        (working copy)
3662@@ -3,6 +3,10 @@
3663 >>> from django.newforms import *
3664 >>> import datetime
3665 >>> import re
3666+>>> try:
3667+...     from decimal import Decimal
3668+... except ImportError:
3669+...     from django.utils.decimal import Decimal
3670 
3671 ###########
3672 # Widgets #
3673@@ -988,6 +992,133 @@
3674 ...
3675 ValidationError: [u'Ensure this value is less than or equal to 20.']
3676 
3677+# FloatField ##################################################################
3678+
3679+>>> f = FloatField()
3680+>>> f.clean('')
3681+Traceback (most recent call last):
3682+...
3683+ValidationError: [u'This field is required.']
3684+>>> f.clean(None)
3685+Traceback (most recent call last):
3686+...
3687+ValidationError: [u'This field is required.']
3688+>>> f.clean('1')
3689+1.0
3690+>>> isinstance(f.clean('1'), float)
3691+True
3692+>>> f.clean('23')
3693+23.0
3694+>>> f.clean('3.14')
3695+3.1400000000000001
3696+>>> f.clean('a')
3697+Traceback (most recent call last):
3698+...
3699+ValidationError: [u'Enter a number.']
3700+>>> f.clean('1.0 ')
3701+1.0
3702+>>> f.clean(' 1.0')
3703+1.0
3704+>>> f.clean(' 1.0 ')
3705+1.0
3706+>>> f.clean('1.0a')
3707+Traceback (most recent call last):
3708+...
3709+ValidationError: [u'Enter a number.']
3710+
3711+>>> f = FloatField(required=False)
3712+>>> f.clean('')
3713+
3714+>>> f.clean(None)
3715+
3716+>>> f.clean('1')
3717+1.0
3718+
3719+FloatField accepts min_value and max_value just like IntegerField:
3720+>>> f = FloatField(max_value=1.5, min_value=0.5)
3721+
3722+>>> f.clean('1.6')
3723+Traceback (most recent call last):
3724+...
3725+ValidationError: [u'Ensure this value is less than or equal to 1.5.']
3726+>>> f.clean('0.4')
3727+Traceback (most recent call last):
3728+...
3729+ValidationError: [u'Ensure this value is greater than or equal to 0.5.']
3730+>>> f.clean('1.5')
3731+1.5
3732+>>> f.clean('0.5')
3733+0.5
3734+
3735+# DecimalField ################################################################
3736+
3737+>>> f = DecimalField(max_digits=4, decimal_places=2)
3738+>>> f.clean('')
3739+Traceback (most recent call last):
3740+...
3741+ValidationError: [u'This field is required.']
3742+>>> f.clean(None)
3743+Traceback (most recent call last):
3744+...
3745+ValidationError: [u'This field is required.']
3746+>>> f.clean('1')
3747+Decimal("1")
3748+>>> isinstance(f.clean('1'), Decimal)
3749+True
3750+>>> f.clean('23')
3751+Decimal("23")
3752+>>> f.clean('3.14')
3753+Decimal("3.14")
3754+>>> f.clean('a')
3755+Traceback (most recent call last):
3756+...
3757+ValidationError: [u'Enter a number.']
3758+>>> f.clean('1.0 ')
3759+Decimal("1.0")
3760+>>> f.clean(' 1.0')
3761+Decimal("1.0")
3762+>>> f.clean(' 1.0 ')
3763+Decimal("1.0")
3764+>>> f.clean('1.0a')
3765+Traceback (most recent call last):
3766+...
3767+ValidationError: [u'Enter a number.']
3768+>>> f.clean('123.45')
3769+Traceback (most recent call last):
3770+...
3771+ValidationError: [u'Ensure that there are no more than 4 digits in total.']
3772+>>> f.clean('1.234')
3773+Traceback (most recent call last):
3774+...
3775+ValidationError: [u'Ensure that there are no more than 2 decimal places.']
3776+>>> f.clean('123.4')
3777+Traceback (most recent call last):
3778+...
3779+ValidationError: [u'Ensure that there are no more than 2 digits before the decimal point.']
3780+>>> f = DecimalField(max_digits=4, decimal_places=2, required=False)
3781+>>> f.clean('')
3782+
3783+>>> f.clean(None)
3784+
3785+>>> f.clean('1')
3786+Decimal("1")
3787+
3788+DecimalField accepts min_value and max_value just like IntegerField:
3789+>>> f = DecimalField(max_digits=4, decimal_places=2, max_value=Decimal('1.5'), min_value=Decimal('0.5'))
3790+
3791+>>> f.clean('1.6')
3792+Traceback (most recent call last):
3793+...
3794+ValidationError: [u'Ensure this value is less than or equal to 1.5.']
3795+>>> f.clean('0.4')
3796+Traceback (most recent call last):
3797+...
3798+ValidationError: [u'Ensure this value is greater than or equal to 0.5.']
3799+>>> f.clean('1.5')
3800+Decimal("1.5")
3801+>>> f.clean('0.5')
3802+Decimal("0.5")
3803+
3804 # DateField ###################################################################
3805 
3806 >>> import datetime
3807Index: tests/regressiontests/decimal_vs_float/__init__.py
3808===================================================================
3809Index: tests/regressiontests/decimal_vs_float/tests.py
3810===================================================================
3811--- tests/regressiontests/decimal_vs_float/tests.py     (revision 0)
3812+++ tests/regressiontests/decimal_vs_float/tests.py     (revision 0)
3813@@ -0,0 +1,36 @@
3814+r"""
3815+Create a manipulator that has a DecimalField and a FloatField
3816+
3817+>>> from django import oldforms
3818+>>> class TestManipulator(oldforms.Manipulator):
3819+...     def __init__(self):
3820+...         self.fields = (
3821+...             oldforms.DecimalField(field_name="decimal", max_digits=4, decimal_places=2),
3822+...             oldforms.FloatField(field_name="float"),
3823+...         )
3824+...
3825+
3826+Test that the field validation works, and that the appropriate types are returned from the fields.
3827+
3828+>>> from django.utils.datastructures import MultiValueDict
3829+>>> manipulator = TestManipulator()
3830+>>> data = MultiValueDict({'decimal': ["abc"], 'float': ["abc"]})
3831+>>> manipulator.get_validation_errors(data)
3832+{'decimal': ['Please enter a valid decimal number.'], 'float': ['Please enter a valid floating point number.']}
3833+>>> data = MultiValueDict({'decimal': ["0.2123"], 'float': ["0.200"]})
3834+>>> manipulator.get_validation_errors(data)
3835+{'decimal': ['Please enter a valid decimal number with at most 4 total digits.']}
3836+>>> data = MultiValueDict({'decimal': ["0.212"], 'float': ["0.200"]})
3837+>>> manipulator.get_validation_errors(data)
3838+{'decimal': ['Please enter a valid decimal number with at most 2 decimal places.']}
3839+>>> data = MultiValueDict({'decimal': ["0.20"], 'float': ["0.200"]})
3840+>>> manipulator.get_validation_errors(data)
3841+{}
3842+>>> manipulator.do_html2python(data)
3843+>>> data
3844+<MultiValueDict: {'decimal': [Decimal("0.20")], 'float': [0.20000000000000001]}>
3845+"""
3846+
3847+if __name__ == "__main__":
3848+    import doctest
3849+    doctest.testmod()
3850Index: tests/regressiontests/decimal_vs_float/models.py
3851===================================================================
3852--- tests/regressiontests/decimal_vs_float/models.py    (revision 0)
3853+++ tests/regressiontests/decimal_vs_float/models.py    (revision 0)
3854@@ -0,0 +1,49 @@
3855+from django.db import models
3856+try:
3857+    from decimal import Decimal
3858+except ImportError:
3859+    from django.utils.decimal import Decimal
3860+
3861+class DecimalVsFloat(models.Model):
3862+    fixed = models.DecimalField(max_digits=3, decimal_places=1, null=True)
3863+    floating = models.FloatField(null=True)
3864+
3865+    def __str__(self):
3866+        return "%r %r" % (self.fixed, self.floating)
3867+
3868+__test__ = {'ROUNDTRIP_TESTS': r"""
3869+
3870+Create some useful numbers for testing against
3871+
3872+>>> fixed = Decimal('0.2')
3873+>>> floating = 1.2 - 1.0
3874+>>> delta = 5e-17
3875+
3876+Ensure the numbers precisely survive a round-trip to the database.
3877+
3878+>>> n = DecimalVsFloat.objects.create(fixed=fixed, floating=floating)
3879+>>> n = DecimalVsFloat.objects.get(pk=n.id)
3880+>>> type(n.fixed) == Decimal
3881+True
3882+>>> type(n.floating) == float
3883+True
3884+>>> n.fixed
3885+Decimal("0.2")
3886+
3887+Need to do a delta test here because MySQL seems to convert 0.19999999999999996 to 0.20000000000000001
3888+
3889+>>> n.floating + delta >= floating >= n.floating - delta
3890+True
3891+>>> n = DecimalVsFloat.objects.create(fixed=None, floating=None)
3892+>>> print DecimalVsFloat.objects.get(pk=n.id)
3893+None None
3894+
3895+
3896+Note: if you assign a float to a DecimalField or a Decimal to a FloatField,
3897+that's your own problem; the behaviour will depend on the database.
3898+
3899+"""}
3900+
3901+if __name__ == "__main__":
3902+    import doctest
3903+    doctest.testmod()
3904Index: docs/model-api.txt
3905===================================================================
3906--- docs/model-api.txt  (revision 4439)
3907+++ docs/model-api.txt  (working copy)
3908@@ -184,6 +184,33 @@
3909 The admin represents this as two ``<input type="text">`` fields, with
3910 JavaScript shortcuts.
3911 
3912+``DecimalField``
3913+~~~~~~~~~~~~~~
3914+
3915+A fixed-precision decimal number, represented in Python by a ``Decimal`` instance.
3916+Has two **required** arguments:
3917+
3918+    ======================  ===================================================
3919+    Argument                Description
3920+    ======================  ===================================================
3921+    ``max_digits``          The maximum number of digits allowed in the number.
3922+
3923+    ``decimal_places``      The number of decimal places to store with the
3924+                            number.
3925+    ======================  ===================================================
3926+
3927+For example, to store numbers up to 999 with a resolution of 2 decimal places,
3928+you'd use::
3929+
3930+    models.DecimalField(..., max_digits=5, decimal_places=2)
3931+
3932+And to store numbers up to approximately one billion with a resolution of 10
3933+decimal places::
3934+
3935+    models.DecimalField(..., max_digits=19, decimal_places=10)
3936+
3937+The admin represents this as an ``<input type="text">`` (a single-line input).
3938+
3939 ``EmailField``
3940 ~~~~~~~~~~~~~~
3941 
3942@@ -281,27 +308,8 @@
3943 ``FloatField``
3944 ~~~~~~~~~~~~~~
3945 
3946-A floating-point number. Has two **required** arguments:
3947+A floating-point number represented in Python by a ``float`` instance.
3948 
3949-    ======================  ===================================================
3950-    Argument                Description
3951-    ======================  ===================================================
3952-    ``max_digits``          The maximum number of digits allowed in the number.
3953-
3954-    ``decimal_places``      The number of decimal places to store with the
3955-                            number.
3956-    ======================  ===================================================
3957-
3958-For example, to store numbers up to 999 with a resolution of 2 decimal places,
3959-you'd use::
3960-
3961-    models.FloatField(..., max_digits=5, decimal_places=2)
3962-
3963-And to store numbers up to approximately one billion with a resolution of 10
3964-decimal places::
3965-
3966-    models.FloatField(..., max_digits=19, decimal_places=10)
3967-
3968 The admin represents this as an ``<input type="text">`` (a single-line input).
3969 
3970 ``ImageField``
3971Index: docs/forms.txt
3972===================================================================
3973--- docs/forms.txt      (revision 4439)
3974+++ docs/forms.txt      (working copy)
3975@@ -546,6 +546,7 @@
3976     * isValidANSIDate
3977     * isValidANSITime
3978     * isValidEmail
3979+    * isValidFloat
3980     * isValidImage
3981     * isValidImageURL
3982     * isValidPhone
3983@@ -635,10 +636,10 @@
3984     Takes an integer argument and when called as a validator, checks that the
3985     field being validated is a power of the integer.
3986 
3987-``IsValidFloat``
3988+``IsValidDecimal``
3989     Takes a maximum number of digits and number of decimal places (in that
3990-    order) and validates whether the field is a float with less than the
3991-    maximum number of digits and decimal place.
3992+    order) and validates whether the field is a decimal with no more than the
3993+    maximum number of digits and decimal places.
3994 
3995 ``MatchesRegularExpression``
3996     Takes a regular expression (a string) as a parameter and validates the