Skip to content

Instantly share code, notes, and snippets.

@Linuxpizi
Created June 28, 2020 10:45
Show Gist options
  • Save Linuxpizi/959989c4e3a7c24af11aa3e2fe5436e5 to your computer and use it in GitHub Desktop.
Save Linuxpizi/959989c4e3a7c24af11aa3e2fe5436e5 to your computer and use it in GitHub Desktop.
human file type

可阅读的文件大小显示

注:原文地址

/**
 * 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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment