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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | 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 ); } } } |
Please login to continue.