Skip to content

Instantly share code, notes, and snippets.

@minghao51
Last active October 17, 2024 02:35
Show Gist options
  • Save minghao51/59b987fae6b9620f284867705d709c46 to your computer and use it in GitHub Desktop.
Save minghao51/59b987fae6b9620f284867705d709c46 to your computer and use it in GitHub Desktop.
This script defines a function human_format that converts a large number into a readable format with suffixes like K (thousand), M (million), etc. It takes three parameters: num (the number), precision (decimal places), and suffixes (list of suffixes). The function calculates the appropriate suffix and formats the number accordingly. Example: hu…
# python number formatter into string with unit
def human_format(num, precision=2, suffixes=['', 'K', 'M', 'G', 'T', 'P']):
m = sum([abs(num/1000.0**x) >= 1 for x in range(1, len(suffixes))])
return f'{num/1000.0**m:.{precision}f}{suffixes[m]}'
print('the answer is %s' % human_format(7454538))
# prints 'the answer is 7.45M'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment