A universal function that converts the passed in number of bytes to the best format (bytes/ KB/MB/GB/TB) so that the resulting value has a non-zero integer part as small as possible.
Syntax
pm_size_pretty_printing ($bytes, $addB, $precision)
Parameters
bytes
An integer value that specifies the number of bytes.
addB
A boolean value that is true if the 'bytes' suffix should be added to the resulting string in addition to the 'kilo'/'mega'/'giga'/'tera' word, false otherwise. The default setting is false.
precision
A string value that specifies precision of the resulting value to show. It is set to -1 by default (only the integer part of the value should be shown).
Returns
A string value that holds the passed in number of bytes transferred to the best format and output as specified.
Code Example
$num_bytes_to_print = pm_size_pretty_printing (1023, true, 2);
$num_bytes_to_print1 = pm_size_mb_printing (5000, true, 2);
$num_bytes_to_print2 = pm_size_mb_printing (5000000,true);
$num_bytes_to_print3 = pm_size_mb_printing (5000000000, false, 2);
$num_bytes_to_print4 = pm_size_mb_printing (5000000000000);
echo $num_bytes_to_print;
echo $num_bytes_to_print1;
echo $num_bytes_to_print2;
echo $num_bytes_to_print3;
echo $num_bytes_to_print4;
// the result will look as follows:
// 1023 bytes
// 4.88 kilobytes
// 5. megabytes
// 4.65 giga
// 5. tera
Remarks
The above code snippet shows the results of four invocations of this function, each time with different parameters.
If the bytes parameter is less than 1024 bytes (KB), the function returns a string with an integer formatted number of bytes. The precision parameter is not considered.
In case the precision parameter is a zero or a positive value, the function calculates the float number in KB/MB/GB/TB (the best format is selected). Then the function trims the resulting value from the right so that only the required number of fractional digits is left.
In case the precision parameter is set to a negative value or not specified, the function transfers the passed in number of bytes to KB/MB/GB/TB (the best format is selected) and then rounds up the result to its integer part. The resulting string contains an integer part of the value and a dot delimiter, the fractional part of the value is missing.
If the addB parameter is set to true, then the string contains the value and the relevant description (kilobytes, megabytes, gigabytes, terabytes). In case addB is set to false, the 'bytes' suffix is missing, and the string contains the short description (kilo, mega, giga, tera).
Include: pm.php.