Skip to content

Instantly share code, notes, and snippets.

@KD-MM2
Last active April 8, 2023 20:02
Show Gist options
  • Save KD-MM2/b740fb058494ab19b2e5ce3a7cb049a2 to your computer and use it in GitHub Desktop.
Save KD-MM2/b740fb058494ab19b2e5ce3a7cb049a2 to your computer and use it in GitHub Desktop.
parse number and format number
# fmt_num(1000)
# result: 1M
# type(fmt_num(1000))
# result: <class 'str'>
def fmt_num(num):
suffixes = ["", "K", "M", "B", "T"]
suffix_index = 0
while abs(num) >= 1000 and suffix_index < len(suffixes)-1:
suffix_index += 1 # increment the suffix index
num /= 1000.0 # divide by 1000 to get the number in the next magnitude
return f"{num:.0f}{suffixes[suffix_index]}"
# parse_num(1k) or parse_num(1K)
# result: 1000
# type(parse_num(1k))
# result: <class 'int'>
def parse_num(string):
suffixes = {"K": 1000, "M": 1000000, "B": 1000000000, "T": 1000000000000}
string = string.upper()
if string[-1] in suffixes:
return int(float(string[:-1]) * suffixes[string[-1]])
else:
return int(string)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment