Skip to content

Instantly share code, notes, and snippets.

@aglove2189
Last active April 25, 2023 15:51
Show Gist options
  • Save aglove2189/9f9faf08f9dd6f5e9a1efe4b7ca9d4cf to your computer and use it in GitHub Desktop.
Save aglove2189/9f9faf08f9dd6f5e9a1efe4b7ca9d4cf to your computer and use it in GitHub Desktop.
numerize - shorthand format of numbers for humans
import math
def numerize(num, precision=1):
if num == 0:
return "0"
num = float(f"{num:.3g}")
m = int(math.log10(abs(num)) // 3)
numf = f"{num / 1000.0**m:.{precision}f}".rstrip("0").rstrip(".")
return f"{numf}{['', 'K', 'M', 'B', 'T', 'G'][m]}"
assert numerize(999999) == "1M"
assert numerize(999499) == "999K"
assert numerize(9994) == "10K"
assert numerize(9900) == "9.9K"
assert numerize(6543165413) == "6.5B"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment