[Answered ]-Django best practice to round decimals: frontend or backend?


Considering that this is purely a presentation issue, my instinct would be keep it in the templates. That said, the templates should be as dumb as possible, and you probably don’t want to hard code your decimal place counts as magic numbers all over your templates.

I would probably do something like the following:

  • Don’t process any decimal place stuff in your views, unless it’s part of your calculation logic.
  • Write a custom template filter that formats your floats based on parameters defined in your settings.py
  • Write a custom JavaScript function that does the same
  • Use your new filter and function to manipulate decimals as they appear in templates and AJAX callbacks.

That way your keep all your presentation logic at the template level, but you still maintain DRY principles. It still means lots of edits to your templates and JavaScript, but I can’t really think of any cleaner way to do it without getting into really hacky territory.

Leave a comment