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?
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.
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With