注:原文地址
/**
* Converts a long string of bytes into a readable format e.g KB, MB, GB, TB, YB
*
* @param {Int} num The number of bytes.
*/
function readableBytes(bytes) {
var i = Math.floor(Math.log(bytes) / Math.log(1024)),
sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
return (bytes / Math.pow(1024, i)).toFixed(2) * 1 + ' ' + sizes[i];
}
/**
* Converts a long string of bytes into a readable format e.g KB, MB, GB, TB, YB
*
* @param {Int} num The number of bytes.
*/
function readableBytes(num) {
var neg = num < 0;
var units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
if (neg){
num = -num;
}
if (num < 1){
return (neg ? '-' : '') + num + ' B';
}
var exponent = Math.min(Math.floor(Math.log(num) / Math.log(1000)), units.length - 1);
num = Number((num / Math.pow(1000, exponent)).toFixed(2));
var unit = units[exponent];
return (neg ? '-' : '') + num + ' ' + unit;
}