JavaScript 字节单位换算函数(bytes,KB)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_32279193/article/details/80983202
函数:
var byteConvert = function(bytes) {
    if (isNaN(bytes)) {
        return '';
    }
    var symbols = ['bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
    var exp = Math.floor(Math.log(bytes)/Math.log(2));
    if (exp < 1) {
        exp = 0;
    }
    var i = Math.floor(exp / 10);
    bytes = bytes / Math.pow(2, 10 * i);

    if (bytes.toString().length > bytes.toFixed(2).toString().length) {
        bytes = bytes.toFixed(2);
    }
    return bytes + ' ' + symbols[i];
};
调用
byteConvert(bytes);

猜你喜欢

转载自blog.csdn.net/qq_32279193/article/details/80983202