LoginSignup
15
16

More than 5 years have passed since last update.

バイト数をキロバイト・メガバイト・ギガバイトなどの書式に変換する関数

Last updated at Posted at 2012-01-20
<?php
/**
 * バイト数をフォーマットする
 * @param integer $bytes
 * @param integer $precision
 * @param array $units
 */
function formatBytes($bytes, $precision = 2, array $units = null)
{
    if ( abs($bytes) < 1024 )
    {
        $precision = 0;
    }

    if ( is_array($units) === false )
    {
        $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');
    }

    if ( $bytes < 0 )
    {
        $sign = '-';
        $bytes = abs($bytes);
    }
    else
    {
        $sign = '';
    }

    $exp   = floor(log($bytes) / log(1024));
    $unit  = $units[$exp];
    $bytes = $bytes / pow(1024, floor($exp));
    $bytes = sprintf('%.'.$precision.'f', $bytes);
    return $sign.$bytes.' '.$unit;
}

使い方

<?php
var_dump(formatBytes(1)); // 1 B

var_dump(formatBytes(1024)); // 1 KB

// 少数を出す
var_dump(formatBytes(1024, 2)); // 1.00 KB

// 単位の文言をカスタマイズ
var_dump(formatBytes(1024, 2, array('バイト', 'キロバイト', 'メガバイト'))); // 1.00 キロバイト
PHPUnit用テストコード
<?php
class FormatBytesTest extends PHPUnit_Framework_TestCase
{
    /**
     * @dataProvider data4testFormatBytes
     */
    public function testFormatBytes($expect, $bytes, $precision, $units)
    {
        $actual = formatBytes($bytes, $precision, $units);
        $this->assertSame($expect, $actual);
    }

    public static function data4testFormatBytes()
    {
        return array(
            array('1 B', 1, 0, null),
            array('-1 B', -1, 0, null),
            array('-1 KB', -1024, 0, null),
            array('-1.0 KB', -1024, 1, null),
            array('1.5 KB', 1536, 1, null),
            array('1.50 KB', 1536, 2, null),
            array('10 バイト', 10, 0, array('バイト')),
            array('1 ギガバイト', 1073741824, 0, array('バイト', 'キロバイト', 'メガバイト', 'ギガバイト')),
        );
    }
}
15
16
1

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
15
16