[Answer]-Using DecimalField displaying with right precision

1👍

Change the decimal places of the field

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

0👍

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.

Leave a comment