Last active
April 29, 2024 20:08
-
-
Save ElectroDrome/fbc14db2ea5be7568e0f726a81d27630 to your computer and use it in GitHub Desktop.
Python: Format a number of bytes into a human readable format (non looping solution)
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
def format_bytes(num, suffix='B'): | |
magnitude = int(math.floor(math.log(num, 1024))) | |
val = num / math.pow(1024, magnitude) | |
if magnitude > 7: | |
return '{:.1f}{}{}'.format(val, 'Yi', suffix) | |
return '{:3.1f}{}{}'.format(val, ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi'][magnitude], suffix) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment