返回介绍

size_format()

发布于 2017-09-11 10:28:00 字数 3077 浏览 1089 评论 0 收藏 0

size_format( int|string $bytes,  int $decimals )

Convert number of bytes largest unit 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 TB 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.


参数

$bytes

(int|string) (Required) Number of bytes. Note max integer size for integers.

$decimals

(int) (Optional) Precision of number of decimal places. Default 0.


返回值

(string|false) False on failure. Number string on success.


源代码

File: wp-includes/functions.php

function size_format( $bytes, $decimals = 0 ) {
	$quant = array(
		'TB' => TB_IN_BYTES,
		'GB' => GB_IN_BYTES,
		'MB' => MB_IN_BYTES,
		'KB' => KB_IN_BYTES,
		'B'  => 1,
	);

	if ( 0 === $bytes ) {
		return number_format_i18n( 0, $decimals ) . ' B';
	}

	foreach ( $quant as $unit => $mag ) {
		if ( doubleval( $bytes ) >= $mag ) {
			return number_format_i18n( $bytes / $mag, $decimals ) . ' ' . $unit;
		}
	}

	return false;
}

更新日志

Versiondescription
2.3.0Introduced.

相关函数

Uses

  • wp-includes/functions.php: number_format_i18n()

Used By

  • wp-admin/includes/template.php: wp_import_upload_form()
  • wp-admin/includes/media.php: attachment_submitbox_metadata()
  • wp-admin/includes/media.php: media_upload_form()
  • wp-includes/media.php: wp_prepare_attachment_for_js()
  • wp-includes/media-template.php: wp_print_media_templates()

User Contributed Notes

  1. Skip to note content You must log in to vote on the helpfulness of this noteVote results for this note: 0You must log in to vote on the helpfulness of this note Contributed by 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"
    

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文