size_format()
云策文档标注
概述
size_format() 函数用于将字节数转换为适合的最大单位,以提升可读性,例如将 1024 字节显示为 1 KB。它支持从字节到 YB 的单位转换,并考虑了 PHP 整数限制。
关键要点
- 功能:将字节数转换为人类可读的字符串,如 1 KB、1 MB,支持 YB 等大单位。
- 参数:$bytes(必需,整数或字符串,注意 PHP 整数大小限制),$decimals(可选,小数位数,默认 0)。
- 返回值:成功时返回格式化字符串,失败时返回 false。
- 注意事项:PHP 整数通常为 32 位,大数值建议使用字符串以避免溢出;技术上正确单位应为 KiB、MiB 等。
代码示例
$file_size = 1229; // filesize in bytes
echo size_format( $file_size, $decimals = 2 );
// displays "1.20 kB"
原文内容
Converts a number of bytes to the largest unit the bytes will fit into.
Description
It is easier to read 1 KB than 1024 bytes and 1 MB than 1048576 bytes. Converts number of bytes to human readable number by taking the number of that unit that the bytes will go into it. Supports YB value.
Please note that integers in PHP are limited to 32 bits, unless they are on 64 bit architecture, then they have 64 bit size. If you need to place the larger size then what PHP integer type will hold, then use a string. It will be converted to a double, which should always have 64 bit length.
Technically the correct unit names for powers of 1024 are KiB, MiB etc.
Parameters
$bytesint|stringrequired-
Number of bytes. Note max integer size for integers.
$decimalsintoptional-
Precision of number of decimal places. Default 0.
Source
function size_format( $bytes, $decimals = 0 ) {
$quant = array(
/* translators: Unit symbol for yottabyte. */
_x( 'YB', 'unit symbol' ) => YB_IN_BYTES,
/* translators: Unit symbol for zettabyte. */
_x( 'ZB', 'unit symbol' ) => ZB_IN_BYTES,
/* translators: Unit symbol for exabyte. */
_x( 'EB', 'unit symbol' ) => EB_IN_BYTES,
/* translators: Unit symbol for petabyte. */
_x( 'PB', 'unit symbol' ) => PB_IN_BYTES,
/* translators: Unit symbol for terabyte. */
_x( 'TB', 'unit symbol' ) => TB_IN_BYTES,
/* translators: Unit symbol for gigabyte. */
_x( 'GB', 'unit symbol' ) => GB_IN_BYTES,
/* translators: Unit symbol for megabyte. */
_x( 'MB', 'unit symbol' ) => MB_IN_BYTES,
/* translators: Unit symbol for kilobyte. */
_x( 'KB', 'unit symbol' ) => KB_IN_BYTES,
/* translators: Unit symbol for byte. */
_x( 'B', 'unit symbol' ) => 1,
);
if ( 0 === $bytes ) {
/* translators: Unit symbol for byte. */
return number_format_i18n( 0, $decimals ) . ' ' . _x( 'B', 'unit symbol' );
}
foreach ( $quant as $unit => $mag ) {
if ( (float) $bytes >= $mag ) {
return number_format_i18n( $bytes / $mag, $decimals ) . ' ' . $unit;
}
}
return false;
}
Skip to note 2 content
Codex
Example
Display the size of a file
$file_size = 1229; // filesize in bytes echo size_format( $file_size, $decimals = 2 ); // displays "1.20 kB"