PHP格式字节转换为Javascript

FFi*_*ish 5 javascript php format bytestring

不是一个问题,而是一种挑战..

我有这个PHP函数,我总是使用,现在我需要它在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];
}
Run Code Online (Sandbox Code Playgroud)

编辑:感谢回复,我提出了更短的内容,但没有精确(如果你有一些想法,请告诉我)

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)];
}
Run Code Online (Sandbox Code Playgroud)

Joh*_*tta 0

测试:

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];
}
Run Code Online (Sandbox Code Playgroud)