Formatting data quantity/capacity as string
Question: A common task in many programs is converting a byte count (such as from a
drive capacity or file size), into a more human readable form. Consider
150000000000 bytes as being more readable as "150 GB", or "139.7 GiB".

Are there any libraries that contain functionality to perform these
conversions? In Python? In C? In pseudocode? Are there any best practises
regarding the "most readable" form, such as number of significant characters,
precision etc.?


Answer: Here's a method that uses logarithms to determine the file size unit exponent:

    
    
    from math import log
    
    byteunits = ('B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB')
    
    def filesizeformat(value):
        exponent = int(log(value, 1024))
        return "%.1f %s" % (float(value) / pow(1024, exponent), byteunits[exponent])
    

