Skip to content
Advertisement

PHP format bytes translation to Javascript

Not really a question but kind of a challenge..

I have this PHP function that I always use and now I need it in Javascript.

function formatBytes($bytes, $precision = 0) {
    $units = array('b', 'KB', 'MB', 'GB', 'TB');
    $bytes = max($bytes, 0);
    $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
    $pow = min($pow, count($units) - 1);
    $bytes /= pow(1024, $pow);
    return round($bytes, $precision) . ' ' . $units[$pow];
}

EDIT: Thanks to the replies I came up with something shorter, but without precision (let me know if you have some second thoughts)

function format_bytes(size){
    var base = Math.log(size) / Math.log(1024);
    var suffixes = ['b', 'KB', 'MB', 'GB', 'TB' , 'PB' , 'EB'];
    return Math.round(Math.pow(1024, base - Math.floor(base)), 0) + ' ' + suffixes[Math.floor(base)];
}

Advertisement

Answer

Tested:

function formatBytes(bytes, precision)
{
    var units = ['b', 'KB', 'MB', 'GB', 'TB'];
    bytes = Math.max(bytes, 0);
    var pwr = Math.floor((bytes ? Math.log(bytes) : 0) / Math.log(1024));
    pwr = Math.min(pwr, units.length - 1);
    bytes /= Math.pow(1024, pwr);
    return Math.round(bytes, precision) + ' ' + units[pwr];
}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement