Skip to content

Instantly share code, notes, and snippets.

@pixelchai
Last active May 8, 2021 02:22
Show Gist options
  • Save pixelchai/eace0b100a381e7cf724612b7309a9d2 to your computer and use it in GitHub Desktop.
Save pixelchai/eace0b100a381e7cf724612b7309a9d2 to your computer and use it in GitHub Desktop.
Return human-readable version of number with suffix. E.g: 30.4k (base 10)
def human_number(num):
"""
return human-readable version of number. E.g: 30.4k
"""
# https://gist.github.com/pixelzery/eace0b100a381e7cf724612b7309a9d2
if num == 0:
return "0"
elif num < 0:
return "-" + human_number(-num)
suffixes = ['', 'k', 'm', 'b', 't']
suf_index = math.floor(math.log(num, 1000))
big = (1000 ** suf_index)
ret = ''
ret += str(num // big)
decimal_part = round((num % big) / (big / 10))
if decimal_part > 0:
ret += '.' + str(decimal_part)
ret += suffixes[suf_index] if suf_index < len(suffixes) else ''
return ret
# tests:
# human_number(0) = 0
# human_number(5) = 5
# human_number(345) = 345
# human_number(3000) = 3k
# human_number(3600) = 3.6k
# human_number(3642) = 3.6k
# human_number(3662) = 3.7k
# human_number(36620) = 36.6k
# human_number(321005) = 321k
# human_number(366200) = 366.2k
# human_number(3662000) = 3.7m
# human_number(-3662000) = -3.7m
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment