MarkO
MarkO

Reputation: 795

Using DecimalField displaying with right precision

In my database I have a field I wan to use for storing credits. Credits are in multiples of 0.5, so for example a person can have 1, 1.5 10 or 100 etc

Have I chosen the right field in the database for this?....

 models.DecimalField(max_digits=10, decimal_places=5,
                                      null=True, blank=True)

Also on showing the balance I do the following....

 def _balance(self):
        aggregates = self.transactions.aggregate(sum=Sum('amount'))
        sum = aggregates['sum']
        return D('0') if sum is None else sum

Which gives me for example 10.00000 which is not what I want. I would like 10 or if it had half 10.5 etc.

Upvotes: 0

Views: 784

Answers (2)

little_birdie
little_birdie

Reputation: 5857

Django's DecimalField pads the value out to make a fixed length decimal.. eg if you set decimal_places=1, you will always get one digit after the decimal point, even if it's zero.

The way I fixed this for myself was to override the behavior in models.DecimalField, to make my own field VariableDecimalField, as follows:

class VariableDecimalField(models.DecimalField):

  def get_db_prep_save(self, value, connection):
    s = str(value)
    return self.to_python(s.rstrip('0').rstrip('.') if '.' in s else s)

That will strip off any insignificant trailing zero's and will also take away the decimal point if there's no decimal amount.. before it is stored in the database. But if you want the trailing zero to be preserved, if the user entered it that way, just do this.

class VariableDecimalField(models.DecimalField):

  def get_db_prep_save(self, value, connection):
    return self.to_python(value)

Then just use VariableDecimalField instead of DecimalField.

Upvotes: 0

catherine
catherine

Reputation: 22808

Change the decimal places of the field

 models.DecimalField(max_digits=10, decimal_places=1,
                                  null=True, blank=True)

Upvotes: 1

Related Questions