Last active
March 22, 2025 22:34
-
-
Save Abdelkrim/02e604fc38e7f35969e5552f13e4af0a to your computer and use it in GitHub Desktop.
format values per thousands using python 3 : K-thousands, M-millions, B-billions.
This file contains hidden or 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
def sizeof_number(number, currency=None): | |
""" | |
format values per thousands : K-thousands, M-millions, B-billions. | |
parameters: | |
----------- | |
number is the number you want to format | |
currency is the prefix that is displayed if provided (€, $, £...) | |
""" | |
currency='' if currency is None else currency + ' ' | |
for unit in ['','K','M']: | |
if abs(number) < 1000.0: | |
return f"{currency}{number:6.2f}{unit}" | |
number /= 1000.0 | |
return f"{currency}{number:6.2f}B" | |
if __name__ == "__main__": | |
for i in [-123456789, -1, 3.14, 12, 234, 3456, 45678, 567890, 6789012, 78901234, 890123456, 9012345678, 12345678901, 234567890123]: | |
print(sizeof_number(number=i, currency='€')) | |
""" | |
output | |
------ | |
€ -123.46M | |
€ -1.00 | |
€ 3.14 | |
€ 12.00 | |
€ 234.00 | |
€ 3.46K | |
€ 45.68K | |
€ 567.89K | |
€ 6.79M | |
€ 78.90M | |
€ 890.12M | |
€ 9.01B | |
€ 12.35B | |
€ 234.57B | |
""" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment