Skip to content

Instantly share code, notes, and snippets.

@sawidis
Created June 13, 2012 17:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sawidis/2925471 to your computer and use it in GitHub Desktop.
Save sawidis/2925471 to your computer and use it in GitHub Desktop.
largen number truncator
#!/usr/bin/env python
def humanize_wordcount(value, lower_bound=10**3, upper_bound=10**12):
"""
Similar to humanize's intword. Converts a large integer to a friendly text
representation. For example, 1000 becomes '1K', 1000000 becomes '1M' etc.
"""
try:
value = int(value)
except (TypeError, ValueError):
return value
if value <= lower_bound or value >= upper_bound:
return value
scaling_factor, symbol = (10**3, 'K') if value < 10**6 else \
(10**6, 'M') if value < 10**9 else \
(10**9, 'B')
new_value = value / float(scaling_factor)
precision = 0 if int(new_value) >= 100 else 1
return '%.*f%s' % (precision, new_value, symbol)
@sawidis
Copy link
Author

sawidis commented Jun 13, 2012

Should remove bound arguments (and hardcode the values, so as to make sure everything words as intended).

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