WordPress at a glance

size_format() WP 1.0

Convert number of bytes largest unit bytes will fit into.

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.

Works based on: number_format_i18n()
✈ 1 time = 0.000025s = very fast | 50000 times = 0.11s = very fast | PHP 7.0.8, WP 4.6

No Hooks.

Return

String/false. False on failure. Number string on success.

Usage

size_format( $bytes, $decimals );
$bytes(int/string) (required)
Number of bytes. Note max integer size for integers.
$decimals(int)
Precision of number of decimal places.
Default: 0

Code of size_format: wp-includes/functions.php VER 5.0.1

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

Related Functions

From tag: upload download (file system)

More from category: Formatting

No comments
    Hello, !     Log In . Register