bytetosize 和 sizetobyte

other-------------->  byte
function covertSizeToByte(size) {
// sizes = ['B','KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
let temp = size;
if (size.endsWith('KB')) {
return parseInt(temp.replace('KB', '')) * 1024
}
if (size.endsWith('MB')) {
return parseInt(temp.replace('MB', '')) * 1024 * 1024
}
if (size.endsWith('GB')) {
return parseInt(temp.replace('GB', '')) * 1024 * 1024 * 1024
}
// 注意 一定要最后执行
if (size.endsWith('B')) {
return parseInt(temp.replace('B', ''))
}

}

/**
* 文件字节转换为单位大小
* @param bytes 文件大小
* @returns 对应的MB保留两位小数
*/
function bytesToSize(bytes) {
if (bytes === '0' || bytes === 0) return '0B';

var k = 1024;

sizes = ['B','KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];

i = Math.floor(Math.log(bytes) / Math.log(k));

return parseFloat(bytes / Math.pow(k, i)).toFixed(2) + sizes[i];
//toPrecision(3) 后面保留一位小数,如1.0GB //return (bytes / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i];
}


原文地址:https://www.cnblogs.com/WhiteHorseIsNotHorse/p/7008198.html