将字节格式化为千字节,兆字节,千兆字节 [英] Format bytes to kilobytes, megabytes, gigabytes

查看:127
本文介绍了将字节格式化为千字节,兆字节,千兆字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

方案:各种文件的大小以字节为单位存储在数据库中.将此大小信息格式化为千字节,兆字节和千兆字节的最佳方法是什么?例如,我有一个MP3,Ubuntu显示为"5.2 MB(5445632字节)".如何在网页上将其显示为"5.2 MB",并以KB为单位显示小于1兆字节的文件,以GB为单位显示1 GB及以上的文件?

Scenario: the size of various files are stored in a database as bytes. What's the best way to format this size info to kilobytes, megabytes and gigabytes? For instance I have an MP3 that Ubuntu displays as "5.2 MB (5445632 bytes)". How would I display this on a web page as "5.2 MB" AND have files less than one megabyte display as KB and files one gigabyte and above display as GB?

推荐答案

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]; 
} 

(取自 php.net ,那里还有许多其他示例,但我最喜欢这个:-)

(Taken from php.net, there are many other examples there, but I like this one best :-)

这篇关于将字节格式化为千字节,兆字节,千兆字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆