0

I needed to have numbers that are not integers but also have halves 0.5 so I switched my model from IntegerField to DecimalField.

However, numbers now show as 5.00 which is way too burdening. What are my options to display the numbers without trailing zeros: 0.5 instead of 0.50and 5 instead of 5.00?

I am interested to know how to structure the framework to make that work - functions, decorators, or some kind of template tags or maybe some kind of localization. Someone that knows better should be able to dissect and explain the best choices.

mgPePe
  • 5,677
  • 12
  • 52
  • 85
  • My model is `decimal_places=2` so `0.333333` i am guessing will be just `0.33`. The other `1001.2` but that's edge case, I don't care so much about it. – mgPePe Jul 28 '14 at 18:08
  • so wait ... do you want halves(ie only 0.5 increments?) ? or do you want hundredths max with zeros chopped off? (ie 0.1 is fine(for 0.10) so is 0.11(for 0.1111) – Joran Beasley Jul 28 '14 at 18:18
  • I am interested in the logistics in implementing a number formatting, rather than going into details on decimal points. I edited the question to be clearer – mgPePe Jul 28 '14 at 18:36
  • One other thing you could try is, if it's only halves, you could multiply all values by a factor of 10 prior to inserting in the database and divide by a factor of 10 when pulling them out. It can be a little confusing though. If it's dollars, one way to think about it would be as "cents" instead. For instance $0.5 == 50 cents. – Kevin London Jul 28 '14 at 18:42

1 Answers1

4

To do this in templates, the simplest way is to use the floatformat built-in filter. To do this in code, you have more options - you can either write your own formatting code or import floatformat from django.template.defaultfilters and call it on the decimal value.

In general, DecimalField is a fine choice for this kind of thing, but you shouldn't declare it as more precise than you need.

Peter DeGlopper
  • 36,326
  • 7
  • 90
  • 83
  • To make sure I understand you correctly, I could either use `floatformat` or write my own filter. and then in the code I would do `{{points|myfilter}}`? – mgPePe Jul 28 '14 at 18:44
  • You could write your own filter either way, come to think of it, but registering one is very marginally more complex than just writing a custom formatting function that you can call from within Python. The `{{points|myfilter}}` syntax is only for templates. In Python code you'd want something like `floatformat(points)`. – Peter DeGlopper Jul 28 '14 at 19:00