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

"Nines" bug fix #2

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
21 changes: 9 additions & 12 deletions millify/__init__.py
@@ -1,31 +1,28 @@
import math
import re
from decimal import Decimal

__author__ = "Alexander Zaitsev (azaitsev@gmail.com)"
__copyright__ = "Copyright 2018, azaitsev@gmail.com"
__license__ = "MIT"
__version__ = "0.1.1"


def remove_exponent(d):
"""Remove exponent."""
return d.quantize(Decimal(1)) if d == d.to_integral() else d.normalize()


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)
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)
millidx = 0
while abs(n) >= 1000:
millidx += 1
n = round(n / 1000.0, precision)
if n < 1000:
n = round(n, precision)
result = '{}'.format(n)
if drop_nulls:
result = remove_exponent(Decimal(result))
return '{0}{dx}'.format(result, dx=millnames[millidx])
result = result.rstrip('0').rstrip('.')
return '{}{dx}'.format(result, dx=millnames[millidx])


def prettify(amount, separator=','):
Expand Down