#33232: DecimalField rounding error when upgrading from 3.1 to 3.2 on Postgres
-------------------------------------+-------------------------------------
Reporter: Michał Szczepańczyk | Owner: nobody
Type: Bug | Status: closed
Component: Database layer | Version: 3.2
(models, ORM) |
Severity: Normal | Resolution: invalid
Keywords: decimal, | Triage Stage:
decimalfield, rounding, postgres | Unreviewed
Has patch: 0 | Needs documentation: 0
Needs tests: 0 | Patch needs improvement: 0
Easy pickings: 0 | UI/UX: 0
-------------------------------------+-------------------------------------
Comment (by Alex):
The problem is that right now if I just want to round down the value I
have to get the precision of the field from the model internals, which is
a bit ugly I think. And also this has to be done everywhere where this
field is updated. Why can't we keep everything that
`django.db.backends.utils.format_number` does, but the last line that
converts the value to string? There's a lot of flexibility that Python
`Decimal` provides that's not available in SQL.
The code I had before:
{{{
with localcontext() as ctx:
ctx.rounding = ROUND_DOWN
self.items.update(
split=Decimal("100") * split / self.number_of_items
)
}}}
The code I have to have now:
{{{
with localcontext() as ctx:
value = Decimal("100") * split / number_of_items
ctx.rounding = ROUND_DOWN
max_digits = Model.split.field.max_digits
decimal_places = Model.split.field.decimal_places
if max_digits is not None:
ctx.prec = max_digits
if decimal_places is not None:
value =
value.quantize(Decimal(1).scaleb(-decimal_places))
self.items.update(
split=value
)
}}}
--
Ticket URL: <https://code.djangoproject.com/ticket/33232#comment:6>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.
--
You received this message because you are subscribed to the Google Groups
"Django updates" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/django-updates/065.c129933740ebcd5a791db93a94ae0f89%40djangoproject.com.