Edgar Navasardyan Edgar Navasardyan - 1 year ago 41
jQuery Question

Format integer thousands separator throughout the document

After months of web-development, I find myself completely helpless trying to find a good solution for a simple problem of formatting all the numbers throughout the DOM as I wish. Specifically, I have a js function my_int_formatter(), that I want to apply to all integers after the doc has been loaded. Best descriped by example - I want to do something like


I know the code above won't work, because I have to include 'script' tag, but first, I don't like the messy code, and second, javascript won't recognize python variable

I tried the following way:


<td class = 'my_integer'>{{django_variable}}</td>


// ....
content = $('.my_integer').html();

...but as expected, I got wrong results because the js code applied the same html() content of the first .my_integer element in the DOM chain to all the others. Any ideas how to do this the short and correct way ?

Answer Source

If I understand you correctly, you want to use builtin django.contrib.humanize application: https://docs.djangoproject.com/en/1.9/ref/contrib/humanize/

You can format integers using some predefined filters, for example intcomma:

4500 becomes 4,500.
45000 becomes 45,000.
450000 becomes 450,000.
4500000 becomes 4,500,000.

Usage in your case would be like

{% load humanize %}

Also don't forget to include the app in INSTALLED_APPS

Also this question might be useful