Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python format size application (converting B to KB, MB, GB, TB)

I am trying to write an application to convert bytes to kb to mb to gb to tb. Here's what I have so far:

def size_format(b):     if b < 1000:               return '%i' % b + 'B'     elif 1000 <= b < 1000000:         return '%.1f' % float(b/1000) + 'KB'     elif 1000000 <= b < 1000000000:         return '%.1f' % float(b/1000000) + 'MB'     elif 1000000000 <= b < 1000000000000:         return '%.1f' % float(b/1000000000) + 'GB'     elif 1000000000000 <= b:         return '%.1f' % float(b/1000000000000) + 'TB' 

The problem is, when I try the application I get everything after the decimal zeroing out. example size_format(623) yields '623B' but with size_format(6200), instead of getting '6.2kb' I'm getting '6.0kb'. Any ideas why?

like image 481
user1687654 Avatar asked Sep 21 '12 02:09

user1687654


People also ask

What is MB KB GB TB PB?

A kilobyte (KB) is 1,000 bytes, and one megabyte (MB) is 1,000 kilobytes. One gigabyte (GB) is equal to 1,000 megabytes, while a terabyte (TB) is 1,000 gigabytes.


1 Answers

Fixed version of Bryan_Rch's answer:

def format_bytes(size):     # 2**10 = 1024     power = 2**10     n = 0     power_labels = {0 : '', 1: 'kilo', 2: 'mega', 3: 'giga', 4: 'tera'}     while size > power:         size /= power         n += 1     return size, power_labels[n]+'bytes' 
like image 160
Pietro Battiston Avatar answered Oct 19 '22 23:10

Pietro Battiston