Code

Opened 4 years ago

Closed 4 years ago

Last modified 3 years ago

#14659 closed (invalid)

Assigning floats to DecimalFields

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

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 maraujop 4 years ago.
Patch

Download all attachments as: .zip

Change History (3)

Changed 4 years ago by maraujop

Patch

comment:1 Changed 4 years ago by dmoisset

  • Needs documentation unset
  • Needs tests unset
  • Patch needs improvement unset
  • Resolution set to invalid
  • Status changed from new to closed

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 Changed 3 years ago by jacob

  • milestone 1.3 deleted

Milestone 1.3 deleted

Add Comment

Modify Ticket

Change Properties
<Author field>
Action
as closed
as The resolution will be set. Next status will be 'closed'
The resolution will be deleted. Next status will be 'new'
Author


E-mail address and user name can be saved in the Preferences.

 
Note: See TracTickets for help on using tickets.