Skip to content

Instantly share code, notes, and snippets.

@kipanshi
Created November 3, 2012 15:53
Show Gist options
  • Save kipanshi/4007717 to your computer and use it in GitHub Desktop.
Save kipanshi/4007717 to your computer and use it in GitHub Desktop.
Django float format and intcomma optimization
import cProfile
from django.template.defaultfilters import floatformat as floatformat_django
from django.contrib.humanize.templatetags.humanize import intcomma as intcomma_django
num = 100000
float_num = 1 / 3.0
def floatformat(value, places=2):
"""Display only desired number of deciaml places. Returns string."""
left, right = str(value).split('.')
return '.'.join((left, right[:places]))
def intcomma(value):
"""Add comma on every 10^3. Returns string."""
value = str(value)
dot_position = value.find('.')
if dot_position != -1:
int_part, decimal_part = value[:dot_position], value[dot_position:]
else:
int_part, decimal_part = value, ''
comma_position = int_part.find(',')
if comma_position != -1:
left, right = int_part[:comma_position], int_part[comma_position:]
else:
left, right = int_part, ''
if len(left) > 3:
comma_ready = ''.join((intcomma(left[:-3]), ',', left[-3:], right))
if decimal_part:
return ''.join((comma_ready, decimal_part))
else:
return comma_ready
return value
#===================
# PROFILING RESULTS
#===================
# >>> cProfile.run('for i in xrange(4000): intcomma_django(num)')
# 124002 function calls (120002 primitive calls) in 0.209 seconds
# ^^^^^^ ^^^^^
#
# >>> cProfile.run('for i in xrange(4000): intcomma(num)')
# 36002 function calls (32002 primitive calls) in 0.031 seconds
#
# >>> cProfile.run('for i in xrange(4000): floatformat_django(float_num, 3)')
# 1076002 function calls (1064002 primitive calls) in 1.446 seconds
# ^^^^^^^ ^^^^^ !!!
#
# >>> cProfile.run('for i in xrange(4000): floatformat(float_num, 3)')
# 12002 function calls in 0.022 seconds
@leetrout
Copy link

Thanks for sharing this. I've been using it with much success but just discovered a bug where the negative dash is considered a digit. I forked and updated my gist so you can see the changes I implemented in intcomma.

The bug looks like this:

In [2]: intcomma(-345.123)
Out[2]: '-,345.123'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment