php版本
function formatBytes($bytes, $precision = 2) {
$units = array('B', 'KB', 'MB', 'GB', 'TB');
$bytes = max($bytes, 0);
$pow = floor(($bytes ? log($bytes) : 0) / log(1024));
$pow = min($pow, count($units) - 1);
// Uncomment one of the following alternatives
$bytes /= pow(1024, $pow);
// $bytes /= (1 << (10 * $pow));
return round($bytes, $precision) . ' ' . $units[$pow];
}
Javascript版本
function formatBytes(bytes){
if (bytes === 0) return '0 K';
var k = 1024,
sizes = ['B','K','M','G','T','P','E','Z','Y'],
i = Math.floor(Math.log(bytes) / Math.log(k));
if(i >= sizes.length) i = sizes.length - 1;
return (bytes / Math.pow(k, i)).toPrecision(5) + ' ' + sizes[i];
}
网友评论