Last active
April 6, 2021 19:37
-
-
Save brunomsantiago/8a9eb13c7e6f19454894036af6f23813 to your computer and use it in GitHub Desktop.
human_readable_size
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 human_readable_size(size_bytes, base=1024, decimal_places=2): | |
suffixes = 'B KB MB GB TB PB EB ZB YB'.split(' ') | |
if size_bytes == 0: | |
return '0B' | |
magnitude_index = int(math.floor(math.log(size_bytes, base))) | |
magnitude_bytes = math.pow(base, magnitude_index) | |
size = size_bytes / magnitude_bytes | |
suffix = suffixes[magnitude_index] | |
return f'{size:.{decimal_places}f} {suffix}' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment