-1

I have this function and I want to allow only 2 decimal places for the value.

This is not a model field but it's being calculated from them. What is the right way to do it?

@property
def value(self):
    value = self.average_flow_rate * (self.d_n / 1000) / self.nu
    if 2320 < value < 4000:
        return 4000
    else:
        return value
Kye Russell
  • 3,868
  • 3
  • 19
  • 48
Xhens
  • 810
  • 3
  • 13
  • 29
  • 1
    use built-in method `round(value, 2)` – hadi Jul 20 '17 at 10:01
  • If you want decimals (not floats), use the stdlib's `decimal` module instead (and django DecimalFields for your model) – bruno desthuilliers Jul 20 '17 at 10:13
  • Possible duplicate of [How to round to two decimal places in Python 2.7?](https://stackoverflow.com/questions/17470883/how-to-round-to-two-decimal-places-in-python-2-7) – Sayse Jul 20 '17 at 10:39

1 Answers1

2

This should work like a charm:

round(self.d_n, 2)
Silwest
  • 1,588
  • 1
  • 13
  • 28
  • Thanks. I solved it. The problem was at template rendering where I had put: `{{ form.instance.value|stringformat:"d" }}` instead of ".2f" – Xhens Jul 20 '17 at 11:13