[Django]-Why Sum() in Django returns number with 13 decimal places when evaluating numbers with only 2 decimal places?

4👍

If you’re using SQLite, you should know that it doesn’t support decimal internally, as explained here. That’s why Sum() returns a float.

You should therefore either use python float formatting functions to round total to 2 decimals or you can use the floatformat template filter.

0👍

You could set the total to a string and then send that to your HTML page in the context.

total = cart_items.aggregate(Sum('price'))['price__sum']
total = '{:0.2f}'.format(total)

or if you want it formatted as a string with the dollar symbol and to add commas (for thousands of dollars):

from django.contrib.humanize.templatetags.humanize import intcomma
...
total = cart_items.aggregate(Sum('price'))['price__sum']
total = f"${intcomma('{:0.2f}'.format(total))}"

Leave a comment