I have a fairly extensive Django site that deals with currency amounts that need to be displayed with 2 decimal places, but since there are mathematical operations performed on these amounts, behind the scenes, 4 place decimals are used. Some pages get these amounts via AJAX calls (as JSON) and other pages get them via the standard view => template variable passing. My models use models.DecimalField(max_digits=10, decimal_places=4, default=Decimal('0'))
The site is large enough now that I need to figure out a consistent way to handle this decimal rounding, but no matter which way I do it, it seems awkward. Here are the two ways I can think of, but each seems less than ideal.
Frontend: views leave the decimals unchanged, with 4 places. Templates use the
floatformat:2
filter and JS functions use.toFixed(2)
for the conversion of incoming JSON data. Problem: need to handle the rounding in many places in template code and JS code.Backend: views round all decimals to 2 places and pass them as strings to the templates. Likewise, responses to incoming AJAX calls serialize all decimals to 2 places. Problem: views are now handling formatting instead of templates and special cases cannot be formatted differently in the template.
Is there a "proper, Djangonic" way of handling Decimal rounding?