Opened 13 years ago

Closed 13 years ago

Last modified 13 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

Description

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)

Item.objects.create(weight=100.43)

The patch passes Django tests, regards

Miguel Araujo

Attachments (1)

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

Download all attachments as: .zip

Change History (3)

by Miguel Araujo, 13 years ago

Patch

comment:1 by Daniel F Moisset, 13 years ago

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/decimal.py", 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 by Jacob, 13 years ago

milestone: 1.3

Milestone 1.3 deleted

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