Last active
April 25, 2023 15:51
-
-
Save aglove2189/9f9faf08f9dd6f5e9a1efe4b7ca9d4cf to your computer and use it in GitHub Desktop.
numerize - shorthand format of numbers for humans
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
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