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 import math
def format_size(n): def format_size(n, unit='B'):
''' '''
Takes an integer n, representing a filesize and returns a string 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: Example:
>>> format_size(1000000) >>> format_size(42)
'1.0 MB' '42 B'
>>> format_size(123456)
'123 kB'
>>> format_size(1000*1000)
'1.00 MB'
>>> format_size(1024*1024*1024) >>> 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) size = float(n)
if size > 1000 : PREFIXES = ['', 'k', 'M', 'G', 'T', 'P']
size = str( round( (size/1000), 3 ) ) + " GB"
else : for prefix in PREFIXES:
size = str( math.floor(size) ) + " MB" if size < 1000:
return size 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