首页 > 技术文章 > js字节转换、字节转换GB等

xiangsj 2016-09-23 15:27 原文

//文件大小换算

function bytesToSize(bytes) {
if (bytes === 0) return '0 B';

var k = 1024;

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

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

 

var num = bytes / Math.pow(k, i);
return num.toPrecision(3) + ' ' + sizes[i];

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

推荐阅读