I\'m trying to format numbers. Examples:
1 => 1
12 => 12
123 => 123
1234 => 1,234
12345 => 12,345
It strikes as a
The humanize solution is fine if your website is in English. For other languages, you need another solution: I recommend using Babel. One solution is to create a custom template tag to display numbers properly. Here's how: just create the following file in your_project/your_app/templatetags/sexify.py
:
# -*- coding: utf-8 -*-
from django import template
from django.utils.translation import to_locale, get_language
from babel.numbers import format_number
register = template.Library()
def sexy_number(context, number, locale = None):
if locale is None:
locale = to_locale(get_language())
return format_number(number, locale = locale)
register.simple_tag(takes_context=True)(sexy_number)
Then you can use this template tag in your templates like this:
{% load sexy_number from sexify %}
{% sexy_number 1234.56 %}
Of course you can use variables instead:
{% sexy_number some_variable %}
Note: the context
parameter is currently not used in my example, but I put it there to show that you can easily tweak this template tag to make it use anything that's in the template context.