-1

This is how I get average marks of a bunch of schools

def get_clu_average(self):
    clu_strength = 0
    clu_total = 0
    for school in self.school_set.all():
        clu_strength = clu_strength + school.strength
        clu_total = clu_total + school.get_average() * school.strength
    return clu_total / clu_strength

So the value will be a decimal number. When I directly use that in template I am getting a lot of decimal places. How do I restrict the value to only 2 decimal places?

venkat mani sai
  • 89
  • 1
  • 3
  • 11

1 Answers1

4

You can use the built-in floatformat filter in your template:

{{ value|floatformat:'2' }}     

or limit the precision in your view code by either formatting a string for your context or using a decimal.Decimal instance instead of a float:

val = obj.get_clu_average()

val_str = '{.2f}'.format(val)
# OR
from decimal import Decimal as D
val_dec = D(val).quantize(D('0.01'))
user2390182
  • 72,016
  • 6
  • 67
  • 89