计算字节数函数

var get_readability_size = function ( bytes ) {

var BYTE_UNITS = ['B', 'K', 'M', 'G', 'T', 'E', 'Z', 'Y', 'B', '...'];

bytes = parseInt(bytes);

if (!bytes)
return '0B';

var unit = parseInt(Math.floor(Math.log(bytes) / Math.log(1024))),                 // logaX = logbX / logbA   即 log1024(bytes);
size = bytes / Math.pow(1024, unit),

decimal_size = (Math.floor(size * 100) / 100); // 12.345 -> 12.34

// 如果小数位有值,则保留2位;小数位为0,则不保留 @james
if (decimal_size !== parseInt(decimal_size)) {
size = decimal_size.toFixed(2);
}
// 整数
else {
size = parseInt(size);
}

return size + BYTE_UNITS[unit];
};

posted on 2014-06-04 16:02  rainbow661314  阅读(450)  评论(0)    收藏  举报