有时候我们需要在网页上显示某个文件的大小,或者是其它数据的大小数字。
这个数字往往从跨度很大,如果以B为单位的话可能是个位,如果1G则长达1073741824的数字,这个时候我们就需要根据大小来格式化,比如小于1K则以B为单位显示,小于1M则以KB为单位显示,小于1G则以MB为单位显示,以此类推...
格式化函数参考如下:
<span>//</span><span>格式化size显示</span> <span>function</span> formatSize(<span>$b</span>,<span>$times</span>=0<span>){ </span> <span>if</span>(<span>$b</span>>1024<span>){ </span><span>$temp</span>=<span>$b</span>/1024<span>; </span><span>return</span> formatSize(<span>$temp</span>,<span>$times</span>+1<span>); }</span><span>else</span><span>{ </span><span>$unit</span>='B'<span>; </span><span>switch</span>(<span>$times</span><span>){ </span><span>case</span> '0':<span>$unit</span>='B';<span>break</span><span>; </span><span>case</span> '1':<span>$unit</span>='KB';<span>break</span><span>; </span><span>case</span> '2':<span>$unit</span>='MB';<span>break</span><span>; </span><span>case</span> '3':<span>$unit</span>='GB';<span>break</span><span>; </span><span>case</span> '4':<span>$unit</span>='TB';<span>break</span><span>; </span><span>case</span> '5':<span>$unit</span>='PB';<span>break</span><span>; </span><span>case</span> '6':<span>$unit</span>='EB';<span>break</span><span>; </span><span>case</span> '7':<span>$unit</span>='ZB';<span>break</span><span>; </span><span>default</span>: <span>$unit</span>='单位未知'<span>; } </span><span>return</span> <span>sprintf</span>('%.2f',<span>$b</span>).<span>$unit</span><span>; } }</span>
调用:
<span>echo</span> formatSize('20667564');
结果是:
19.71MB
说明:
其中参数$b是以B为单位的数字,$times是用来标识这个函数递归了多少次的。
其中不常用的单位TB、PB、EB、ZB请参考下面的备注(来源于网络):
1bit(这个比特表示一个二进制数字)1Byte(这个单词音译过来也叫“比特”但是表示一个十六进制的数字)
1B=1Byte=8bit
1 kB = 1024 B (kB - kilobyte) 千
1 MB = 1024 kB (MB - megabyte) 兆
1 GB = 1024 MB (GB - gigabyte) 吉
1 TB = 1024 GB (TB - terabyte) 太
1 PB = 1024 TB (PB - petabyte) 拍
1 EB = 1024 PB (EB - eksabyte) 艾
1 ZB = 1024 EB (ZB - zettabyte) 皆
1 YB = 1024 ZB (YB - yottabyte) 佑
1 BB = 1024 YB (BB - brontobyte)
yotta, 尧[它], Y. 10^21,
zetta, 泽[它], Z. 10^18,
exa, 艾[可萨], E. 10^15,
peta, 拍[它], P. 10^12,
tera, 太[拉], T. 10^9,
giga, 吉[咖], G. 10^6,
mega, 兆,M. 10^3
以上就介绍了PHP格式化(文件)存储数据大小(SIZE)显示,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。