Created
June 13, 2012 17:48
-
-
Save sawidis/2925471 to your computer and use it in GitHub Desktop.
largen number truncator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Should remove bound arguments (and hardcode the values, so as to make sure everything words as intended).