Python format size application (converting B to KB, MB, GB, TB)
def humanbytes(B): 'Return the given bytes as a human friendly KB, MB, GB, or TB string' B = float(B) KB = float(1024) MB = float(KB ** 2) # 1,048,576 GB = float(KB ** 3) # 1,073,741,824 TB = float(KB ** 4) # 1,099,511,627,776 if B < KB: return '{0} {1}'.format(B,'Bytes' if 0 == B > 1 else 'Byte') elif KB <= B < MB: return '{0:.2f} KB'.format(B/KB) elif MB <= B < GB: return '{0:.2f} MB'.format(B/MB) elif GB <= B < TB: return '{0:.2f} GB'.format(B/GB) elif TB <= B: return '{0:.2f} TB'.format(B/TB)tests = [1, 1024, 500000, 1048576, 50000000, 1073741824, 5000000000, 1099511627776, 5000000000000]for t in tests: print '{0} == {1}'.format(t,humanbytes(t))
Output:
1 == 1.0 Byte1024 == 1.00 KB500000 == 488.28 KB1048576 == 1.00 MB50000000 == 47.68 MB1073741824 == 1.00 GB5000000000 == 4.66 GB1099511627776 == 1.00 TB5000000000000 == 4.55 TB
and for future me here it is in Perl too:
sub humanbytes { my $B = shift; my $KB = 1024; my $MB = $KB ** 2; # 1,048,576 my $GB = $KB ** 3; # 1,073,741,824 my $TB = $KB ** 4; # 1,099,511,627,776 if ($B < $KB) { return "$B " . (($B == 0 || $B > 1) ? 'Bytes' : 'Byte'); } elsif ($B >= $KB && $B < $MB) { return sprintf('%0.02f',$B/$KB) . ' KB'; } elsif ($B >= $MB && $B < $GB) { return sprintf('%0.02f',$B/$MB) . ' MB'; } elsif ($B >= $GB && $B < $TB) { return sprintf('%0.02f',$B/$GB) . ' GB'; } elsif ($B >= $TB) { return sprintf('%0.02f',$B/$TB) . ' TB'; }}