Opened 5 years ago

Closed 5 years ago

#30290 closed Cleanup/optimization (wontfix)

Documentation should make clear that values on DecimalField is better to be passed as strings

Reported by: Alexandros Kanterakis Owned by: nobody
Component: Documentation Version: 2.1
Severity: Normal Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: yes UI/UX: no

Description

On the documentation of DecimalField it does not mention that passing values as string instead of float has a significant difference. A user that tests the code in the documentation might come to a surprise to find that the following part raises a ValidationError:

class A(models.Model):
        # A DecimalField as mentioned on the doc
        # "For example, to store numbers up to 999 with a resolution of 2 decimal places, you’d use:"
	f = models.DecimalField(max_digits=5, decimal_places=2) 
A(f=10.1).clean_fields()  # This raises the following exception:
django.core.exceptions.ValidationError: {'f': ['Ensure that there are no more than 2 decimal places.']} 

If the value of f is passed as string, then it works as expected.

A(f="10.1").clean_fields() 

There is a very subtle reference about this on the documentation of the decimal module:

>>> Decimal(3.14)
Decimal('3.140000000000000124344978758017532527446746826171875')

See also discussion in SO: https://stackoverflow.com/questions/52376693/django-strange-decimalfield-validation

Change History (3)

comment:1 by Tim Graham, 5 years ago

Type: UncategorizedCleanup/optimization

Generally the value would be passed as a Decimal rather than as a string so I'm not sure it needs to be documented.

comment:2 by Carlton Gibson, 5 years ago

I'm kind of sympathetic to this, because it may well be the first instance in which beginners come across this kind of computer weirdness.

However... I'm not sure the model field reference is the place to teach this kind of thing and we already like to the FloatFields vs DecimalFields discussion, and from there to the decimal docs.

This discussion (i.e. the decimal docs) is a bit advanced for the situation in mind, so I wonder if linking instead to the Decimal Floating Point Arithmetic section of the Python Tutorial (which itself links back to the decimal docs) wouldn't be a win?

(Still not sure it really gets to the heart of the matter, but it's a question of how much help we can give in this particular location, and without linking to, say, a blog or something which is liable to just disappear...)

Last edited 5 years ago by Carlton Gibson (previous) (diff)

comment:3 by Tim Graham, 5 years ago

Resolution: wontfix
Status: newclosed

Yea, I don't think using strings is a best practice in the first place, so let's not get into the discussion.

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