Formatting data quantity/capacity as string
A common task in many programs is converting a byte count (such as from a drive capacity or开发者_如何学C 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.?
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])
I'm not sure that there is such a thing as best practice here, but there are some issues to consider. There are two questions you need to answer:
- Is it appropriate to use base-1000 or base-1024 units?
- When does precision start to become redundant?
Regarding the use of units, there are two guidelines. Firstly, always use the appropriate binary prefix so at least your users can figure out what is going on. Secondly, go with the principle of least surprise, and use whatever units are common in your problem domain. Thus, if you are reporting a file size on Windows, use base-1024 as that is what Windows uses. If you are reporting RAM sizes, use base-1024, as that is how RAM sizes are always reported. If you are reporting hard-disk sizes, use base-1000, as that is how they are commonly reported.
Regarding precision, I think this is a judgement call. I am loath to report more than one significant digit, because in any situation in which more precision is required, the number of bytes is the measure you want to report.
Well, I usually go for this:
<?php
$factor = 0;
$units = ['B','KiB','MiB','GiB','TiB']
while( $size > 1024 && $factor<count($units-1)) {
$factor++;
$size /= 1024; // or $size >>= 10;
}
echo round($size,2).$units[$factor];
?>
Hope this helps!
精彩评论