Js字节单位换算函数

  1. 字节转换为单位大小
function bytesToSize(bytes) {
    if(bytes === 0) return '0 B';
    var k = 1024;
    var sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
    var i = Math.floor(Math.log(bytes) / Math.log(k));
    return (bytes / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i];
    // return parseFloat(bytes / Math.pow(k, i)).toFixed(2)  + sizes[i];
}
var b = 10000;
console.log(b + '字节数是:' + bytesToSize(b));
//输出 10000字节数是:9.77 KB
  1. 单位大小转换为字节
function sizeToBytes(size) {
    // sizes = ['B','KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
    var temp = size;
    if (size.endsWith('KB')) {
        return parseInt(temp.replace('KB', '')) * 1024
    }else if (size.endsWith('MB')) {
        return parseInt(temp.replace('MB', '')) * 1024 * 1024
    }else if (size.endsWith('GB')) {
        return parseInt(temp.replace('GB', '')) * 1024 * 1024 * 1024
    }else if (size.endsWith('B')) {
        return parseInt(temp.replace('B', ''))
    }else {
        console.log('请输入正确的数值')
    }
}
var s = '16GB';
console.log(s + '是:' + sizeToBytes(s) + '字节');
//输出 16GB是:17179869184字节

你可能感兴趣的:(Js字节单位换算函数)