function format_size

format_size($size, $langcode = NULL)

Generates a string representation for the given byte count.

Parameters

$size: A size in bytes.

$langcode: Optional language code to translate to a language other than what is used to display the page.

Return value

\Drupal\Core\StringTranslation\TranslatableMarkup A translated string representation of the size.

Related topics

Formatting
Functions to format numbers, strings, dates, etc.

File

core/includes/common.inc, line 250
Common functions that many Drupal modules will need to reference.

Code

function format_size($size, $langcode = NULL) {
  if ($size < Bytes::KILOBYTE) {
    return \Drupal::translation()->formatPlural($size, '1 byte', '@count bytes', array(), array('langcode' => $langcode));
  }
  else {
    $size = $size / Bytes::KILOBYTE; // Convert bytes to kilobytes.
    $units = ['KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
    foreach ($units as $unit) {
      if (round($size, 2) >= Bytes::KILOBYTE) {
        $size = $size / Bytes::KILOBYTE;
      }
      else {
        break;
      }
    }
    $args = ['@size' => round($size, 2)];
    $options = ['langcode' => $langcode];
    switch ($unit) {
      case 'KB':
        return new TranslatableMarkup('@size KB', $args, $options);
      case 'MB':
        return new TranslatableMarkup('@size MB', $args, $options);
      case 'GB':
        return new TranslatableMarkup('@size GB', $args, $options);
      case 'TB':
        return new TranslatableMarkup('@size TB', $args, $options);
      case 'PB':
        return new TranslatableMarkup('@size PB', $args, $options);
      case 'EB':
        return new TranslatableMarkup('@size EB', $args, $options);
      case 'ZB':
        return new TranslatableMarkup('@size ZB', $args, $options);
      case 'YB':
        return new TranslatableMarkup('@size YB', $args, $options);
    }
  }
}

© 2001–2016 by the original authors
Licensed under the GNU General Public License, version 2 and later.
Drupal is a registered trademark of Dries Buytaert.
https://api.drupal.org/api/drupal/core!includes!common.inc/function/format_size/8.1.x