Opened 12 years ago

Closed 12 years ago

Last modified 11 years ago

#14659 closed (invalid)

Assigning floats to DecimalFields

Reported by: Miguel Araujo Owned by: Miguel Araujo
Component: Database layer (models, ORM) Version: dev
Severity: Keywords: DecimalField, float
Cc: muchochini@… Triage Stage: Unreviewed
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no


DecimalField does not accept a float as a parameter, as it should be first converted to a string. So if you have DecimalField in a model, you will not be able to assign a float to it.

class Item(models.Model):
    weight = models.DecimalField(max_digits=7, decimal_places = 2)


The patch passes Django tests, regards

Miguel Araujo

Attachments (1)

DecimalField-accepting-floats-with-dots.patch (478 bytes) - added by Miguel Araujo 12 years ago.

Download all attachments as: .zip

Change History (3)

Changed 12 years ago by Miguel Araujo


comment:1 Changed 12 years ago by Daniel F Moisset

Resolution: invalid
Status: newclosed

This follows the same rule as the stdlib Decimal class:

>>> from decimal import Decimal
>>> Decimal(100.43)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.6/", line 649, in __new__
    "First convert the float to a string")
TypeError: Cannot convert float to Decimal.  First convert the float to a string

This rule is explicitly there to avoid nasty and hard to debug bugs: the 100.43 you write in the code is not actually 100.43 (but a very close float value), so you could end up passing a value which is not the one the code leads you to believe. So enforcing the conversion to be explicit is safer.

comment:2 Changed 11 years ago by Jacob

milestone: 1.3

Milestone 1.3 deleted

Note: See TracTickets for help on using tickets.
Back to Top