Commit ed895a6a authored by Mathieu Giraud's avatar Mathieu Giraud Committed by Vidjil Team
Browse files

vidjil_utils.py, format_size: more generic function, constant number of significant digits

parent 78544007
import math
def format_size(n):
def format_size(n, unit='B'):
'''
Takes an integer n, representing a filesize and returns a string
where the size is formatted in M, G, ...
where the size is formatted with the correct SI prefix and
with a constant number of significant digits.
Example:
>>> format_size(1000000)
'1.0 MB'
>>> format_size(42)
'42 B'
>>> format_size(123456)
'123 kB'
>>> format_size(1000*1000)
'1.00 MB'
>>> format_size(1024*1024*1024)
'1.073 GB'
'1.07 GB'
>>> format_size(42*(2**40))
'46.2 TB'
'''
size = math.floor((n/1000)/1000)
if size > 1000 :
size = str( round( (size/1000), 3 ) ) + " GB"
else :
size = str( math.floor(size) ) + " MB"
return size
size = float(n)
PREFIXES = ['', 'k', 'M', 'G', 'T', 'P']
for prefix in PREFIXES:
if size < 1000:
break
size /= 1000
if size > 100 or not prefix:
fmt = '%.0f'
elif size > 10:
fmt = '%.1f'
else:
fmt = '%.2f'
return fmt % size + ' ' + prefix + unit
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment