Skip to content
Advertisement

Javascript Human Readable Filesize

I am currently trying to convert this php function to javascript:

function human_filesize($bytes, $decimals = 2) {
  $sz = 'BKMGTP';
  $factor = floor((strlen($bytes) - 1) / 3);
  return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . @$sz[$factor];
}

Here’s what I have so Far:

function human_filesiz(bytes){
            var decimals = 2;
            var sz = 'BKMGTP';
            var factor = Math.floor((bytes.length - 1) / 3);
            return (bytes / Math.pow(1024, factor));
            //return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . @$sz[$factor];
        }

Im Just struggling with the last line. Any Help Greatly Appreciated.

Advertisement

Answer

Did you have a look at: http://programanddesign.com/js/human-readable-file-size-in-javascript/ They have two version of a Javascript solution for Human Readable Filesize:

function fileSize(size) {
    var i = Math.floor(Math.log(size) / Math.log(1024));
    return (size / Math.pow(1024, i)).toFixed(2) * 1 + ' ' + ['B', 'kB', 'MB', 'GB', 'TB'][i];
}

and

function readableFileSize(size) {
    var units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
    var i = 0;
    while(size >= 1024) {
        size /= 1024;
        ++i;
    }
    return size.toFixed(1) + ' ' + units[i];
}

Update loop criteria to while(size >= 1024 && i < units.length - 1) to prevent undefined after YB or last unit exceeded as mentioned by @holytrousers.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement