Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django DecimalField generating "quantize result has too many digits for current context" error on save

I've got a model like:

class ModelWithDecimal(models.Model):
    value = models.DecimalField(max_digits=2,decimal_places=2)

...yet when I try...

obj = ModelWithDecimal(value="1.5")
obj.save()

I get a quantize result has too many digits for current context error during the save. Shouldn't that be OK - it's less than 2 digits, and less than 2 digits after the decimal-point?

The same error happens with a model:

class ModelWithDecimal(models.Model):
    value = models.DecimalField(max_digits=11,decimal_places=8)

...and attempted instance...

obj = ModelWithDecimal(value="1005.7")
obj.save()

Again, seems it should work: only 4 total digits (less than 11), and only 1 after decimal (less than 8).

What's wrong?

like image 256
gojomo Avatar asked Dec 04 '13 02:12

gojomo


1 Answers

The problem is that all the right-of-the-decimal decimal_places are consumed by every instance, regardless of whether you have non-zero digits there, leaving only (max_digits - decimal_places) digits for left-of-the-decimal.

So for DecimalField(max_digits=2,decimal_places=2), there's room for zero digits to the left of the decimal, and "1.5" won't fit. And for DecimalField(max_digits=11,decimal_places=8), there's room for only three digits to the left of the decimal, and "1005.7" won't fit.

Expand your max_digits and the values will work.

like image 59
gojomo Avatar answered Oct 20 '22 06:10

gojomo