You are here

function format_size in Drupal 7

Same name and namespace in other branches
  1. 8 core/includes/common.inc \format_size()
  2. 4 includes/common.inc \format_size()
  3. 5 includes/common.inc \format_size()
  4. 6 includes/common.inc \format_size()
  5. 9 core/includes/common.inc \format_size()
  6. 10 core/includes/common.inc \format_size()

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

A translated string representation of the size.

Related topics

18 calls to format_size()
color_scheme_form_submit in modules/color/color.module
Form submission handler for color_scheme_form().
CommonSizeTestCase::testCommonFormatSize in modules/simpletest/tests/common.test
Check that format_size() returns the expected string.
CommonSizeTestCase::testCommonParseSizeFormatSize in modules/simpletest/tests/common.test
Cross-test parse_size() and format_size().
DrupalWebTestCase::curlExec in modules/simpletest/drupal_web_test_case.php
Initializes and executes a cURL request.
FileFieldValidateTestCase::testFileMaxSize in modules/file/tests/file.test
Tests the max file size validator.

... See full list

File

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

Code

function format_size($size, $langcode = NULL) {
  if ($size < DRUPAL_KILOBYTE) {
    return format_plural($size, '1 byte', '@count bytes', array(), array(
      'langcode' => $langcode,
    ));
  }
  else {
    $size = $size / DRUPAL_KILOBYTE;

    // Convert bytes to kilobytes.
    $units = array(
      t('@size KB', array(), array(
        'langcode' => $langcode,
      )),
      t('@size MB', array(), array(
        'langcode' => $langcode,
      )),
      t('@size GB', array(), array(
        'langcode' => $langcode,
      )),
      t('@size TB', array(), array(
        'langcode' => $langcode,
      )),
      t('@size PB', array(), array(
        'langcode' => $langcode,
      )),
      t('@size EB', array(), array(
        'langcode' => $langcode,
      )),
      t('@size ZB', array(), array(
        'langcode' => $langcode,
      )),
      t('@size YB', array(), array(
        'langcode' => $langcode,
      )),
    );
    foreach ($units as $unit) {
      if (round($size, 2) >= DRUPAL_KILOBYTE) {
        $size = $size / DRUPAL_KILOBYTE;
      }
      else {
        break;
      }
    }
    return str_replace('@size', round($size, 2), $unit);
  }
}