Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fixing issue 101 (millify template tags) #106

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 27 additions & 15 deletions snippet/templatetags/millify.py
Original file line number Diff line number Diff line change
@@ -1,22 +1,34 @@
from math import floor, log10
import math
import re
from decimal import Decimal

from django import template

register = template.Library()
def remove_exponent(d):
return d.quantize(Decimal(1)) if d == d.to_integral() else d.normalize()


@register.filter
def millify(n):
mill_names = ["", "K", "M"]
def millify(n, precision=0, drop_nulls=True, prefixes=[]):
"""Humanize number."""
millnames = ['', 'k', 'M', 'B', 'T', 'P', 'E', 'Z', 'Y']
if prefixes:
millnames = ['']
millnames.extend(prefixes)
n = float(n)
mill_idx = max(
0,
min(
len(mill_names) - 1,
int(floor(0 if n == 0 else log10(abs(n)) / 3)),
),
)
millidx = max(0, min(len(millnames) - 1,
int(math.floor(0 if n == 0 else math.log10(abs(n)) / 3))))
result = '{:.{precision}f}'.format(n / 10**(3 * millidx), precision=precision)
if drop_nulls:
result = remove_exponent(Decimal(result))
return '{0}{dx}'.format(result, dx=millnames[millidx])


def prettify(amount, separator=','):
"""Separate with predefined separator."""
orig = str(amount)
new = re.sub("^(-?\d+)(\d{3})", "\g<1>{0}\g<2>".format(separator), str(amount))
if orig == new:
return new
else:
return prettify(new)

is_more = "+" if mill_names[mill_idx] else ""

return "{}{:.0f}{}".format(is_more, n / 10 ** (3 * mill_idx), mill_names[mill_idx])