-
Notifications
You must be signed in to change notification settings - Fork 0
humanReadable
holzkohlengrill edited this page Dec 15, 2023
·
2 revisions
UNIT_PREFIXES = [
'', # '' for smallest postfix (-> Byte, ...)
'Ki', # Kibibyte = 2^10 Bytes
'Mi', # Mebibyte = 2^20 Bytes
'Gi', # Gibibyte = 2^30 Bytes
'Ti', # Tebibyte = 2^40 Bytes
'Pi', # Pebibyte = 2^50 Bytes
'Ei', # Exbibyte = 2^60 Bytes
'Zi', # Zebibyte = 2^70 Bytes
'Yi', # Yobibyte = 2*80 Butes
'Bi', # Brobibyte = 2^90 Bytes (from Brontobyte (BB); not yet official SI prefix)
'GPi' # Geopibyte (?) = 2^100 Bytes (from Geopbyte (GPB); not yet official SI prefix)
]
def toHumanReadable(num, suffix='B'):
"""
Converts a number into a human readable format: humanReadableSize(168963795964) -> '157.4 GiB'
Note: we use binary prefixes (-> 1kiB = 1024 Byte)
We expect data type to be int (-> we do not expect "half" bytes) or reasonable convertible to int
:param num: Number to convert
:param suffix: The suffix that will be added to the quantifier
:return: Formatted string
"""
if type(num) == int
count = 0
bit_10 = 10
num_tmp = num
for prefix in UNIT_PREFIXES:
if abs(num_tmp) > 1024:
num_tmp >>= bit_10
count += 1
else:
return "{: .2f} {}{}".format(num/2**(count*bit_10), prefix, suffix)
This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License *.
Code (snippets) are licensed under a MIT License *.
* Unless stated otherwise