Last active
February 17, 2021 07:46
-
-
Save mckabi/100eb7feb2b8830b3954681b135350a1 to your computer and use it in GitHub Desktop.
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 humanize_bytes(nbytes, output_format='%.2f %s%s', suffix=None): | |
if suffix is None: | |
suffix = 'iB' | |
basis = 1024.0 if suffix == 'iB' else 1000.0 | |
for unit in ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z']: | |
if abs(nbytes) < basis: | |
return output_format % (nbytes, unit, suffix) | |
nbytes /= basis | |
return output_format % (nbytes, 'Y', suffix) | |
numbers = [10430, 11000000000, 343100000] | |
assert [humanize_bytes(n) for n in numbers] == ['10.2KiB', '10.2GiB', '327.2MiB'] | |
assert [humanize_bytes(n, suffix='B') for n in numbers] == ['10.4KB', '11.0GB', '343.1MB'] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment