{{{
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
[https://docs.python.org/3/library/decimal.html decimal module]:
{{{
>>> Decimal(3.14)
Decimal('3.140000000000000124344978758017532527446746826171875')
}}}
See also discussion in SO: https://stackoverflow.com/questions/52376693
/django-strange-decimalfield-validation
--
Ticket URL: <https://code.djangoproject.com/ticket/30290>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.
* type: Uncategorized => Cleanup/optimization
Comment:
Generally the value would be passed as a Decimal rather than as a string
so I'm not sure it needs to be documented.
--
Ticket URL: <https://code.djangoproject.com/ticket/30290#comment:1>
Comment (by Carlton Gibson):
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 is a bit advanced for the situation in mind, so I wonder
if linking **instead** to the
[https://docs.python.org/3/tutorial/stdlib2.html#decimal-floating-point-
arithmetic Decimal Floating Point Arithmetic section of the Python
Tutorial] (which itself links back to the `decimal` docs) wouldn't be a
win?
--
Ticket URL: <https://code.djangoproject.com/ticket/30290#comment:2>
* status: new => closed
* resolution: => wontfix
Comment:
Yea, I don't think using strings is a best practice in the first place, so
let's not get into the discussion.
--
Ticket URL: <https://code.djangoproject.com/ticket/30290#comment:3>