def calculateSize(self, bytes):
abbrevs = ["kB", "mB", "gB"]
if (bytes == None):
size = "0 kB"
else:
bytes = float(bytes)
for abbrev in abbrevs:
if (bytes > 1024.0):
bytes = bytes / 1024.0
size = "%.2f %s" % (bytes, abbrev)
return size
This is a simple script. It will divide the given bytes by 1024 until they are not more than 1024 or the last abbreviation is reached. To keep track of the current data size, a abbreviation is added at the end. If you want to add more of those, put them in the "abbrevs" list.
Example usage:
print calculateSize(104857606)
will produce:
C:\>python test.py
100.00 mB