I find hurry.filesize
very useful but it doesn’t give output in decimal?
For example:
JavaScript
x
2
1
print size(4026, system=alternative) gives 3 KB.
2
But later when I add all the values I don’t get the exact sum. For example if the output of hurry.filesize
is in 4 variable and each value is 3. If I add them all, I get output as 15.
I am looking for alternative of hurry.filesize to get output in decimals too.
Advertisement
Answer
This isn’t really hard to implement yourself:
JavaScript
1
9
1
suffixes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB']
2
def humansize(nbytes):
3
i = 0
4
while nbytes >= 1024 and i < len(suffixes)-1:
5
nbytes /= 1024.
6
i += 1
7
f = ('%.2f' % nbytes).rstrip('0').rstrip('.')
8
return '%s %s' % (f, suffixes[i])
9
Examples:
JavaScript
1
13
13
1
>>> humansize(131)
2
'131 B'
3
>>> humansize(1049)
4
'1.02 KB'
5
>>> humansize(58812)
6
'57.43 KB'
7
>>> humansize(68819826)
8
'65.63 MB'
9
>>> humansize(39756861649)
10
'37.03 GB'
11
>>> humansize(18754875155724)
12
'17.06 TB'
13