美文网首页
字节大小转换

字节大小转换

作者: Mr_Laoyu | 来源:发表于2017-10-20 11:00 被阅读0次

php版本

function formatBytes($bytes, $precision = 2) { 
    $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); 

    // Uncomment one of the following alternatives
     $bytes /= pow(1024, $pow);
    // $bytes /= (1 << (10 * $pow)); 

    return round($bytes, $precision) . ' ' . $units[$pow]; 
} 

Javascript版本

function formatBytes(bytes){
    if (bytes === 0) return '0 K';
    var k = 1024,
              sizes = ['B','K','M','G','T','P','E','Z','Y'],
          i = Math.floor(Math.log(bytes) / Math.log(k));
        if(i >= sizes.length) i = sizes.length - 1;
        return (bytes / Math.pow(k, i)).toPrecision(5) + ' ' + sizes[i];
}

相关文章

网友评论

      本文标题:字节大小转换

      本文链接:https://www.haomeiwen.com/subject/kdgmuxtx.html