0
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

バイトから適切なファイル単位に変換する

Last updated at Posted at 2016-04-22

ファイルサイズをバイトで取得した際に適切な単位(MBなど)をつけた文字列で変換するスクリプト。
メガバイトの算出は 2^20 = 1024^2 なのでpowを利用。
ギガバイトなどは上記の応用。

/**
 * ファイルサイズの単位変換
 * @param int $size
 *
 * @return string
 */
function calcFileSize($size)
{
  $b = 1024;    // バイト
  $mb = pow($b, 2);   // メガバイト
  $gb = pow($b, 3);   // ギガバイト

  switch(true){
    case $size >= $gb:
      $target = $gb;
      $unit = 'GB';
      break;
    case $size >= $mb:
      $target = $mb;
      $unit = 'MB';
      break;
    default:
      $target = $b;
      $unit = 'KB';
      break;
  }

  $new_size = round($size / $target, 2);
  $file_size = number_format($new_size, 2, '.', ',') . $unit;

  return $file_size;
}

$size = calcFileSize(1000);
// result -> 0.98KB

$size = calcFileSize(1030);
// result -> 1.01KB

$size = calcFileSize(1000000000000000);
// result -> 931,322.57GB

上記の場合は小数点第2位まで表示し、KB未満は 0.1KB という風に返却となる。
switchの条件文を変更すればTBやbyte単位でも可能。

0
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?