본문으로 건너뛰기

바이트를 KB, MB, GB 등의 Human Readable로 변환

JS작업을 하다보면 .. 바이트 단위의 파일 사이즈등을 MB 등의 단위로 표시해야 할 경우가 있습니다.

그런경우에 사용가능한 .. 변환 함수입니다..

JavaScript
function bytesToHumanSize(bytes) {
    var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
    if (bytes == 0){
        return '0 Byte';
    } 

    var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));

    if (i > 4) {
        return Math.round(bytes / Math.pow(1024, i), 2);
    }

    return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i];
 };