प्रारूप बाइट्स से किलोबाइट, मेगाबाइट, गीगाबाइट


184

परिदृश्य: विभिन्न फ़ाइलों का आकार डेटाबेस में बाइट्स के रूप में संग्रहीत किया जाता है। इस आकार की जानकारी को किलोबाइट, मेगाबाइट और गीगाबाइट्स में प्रारूपित करने का सबसे अच्छा तरीका क्या है? उदाहरण के लिए मेरे पास एक एमपी 3 है जो उबंटू "5.2 एमबी (5445632 बाइट्स)" के रूप में प्रदर्शित करता है। मैं इसे वेब पेज पर "5.2 एमबी" के रूप में कैसे प्रदर्शित करूंगा और इसमें केबी के रूप में एक मेगाबाइट डिस्प्ले से कम फाइलें और एक गीगाबाइट और ऊपर के डिस्प्ले को जीबी के रूप में प्रदर्शित करना होगा?


3
मेरा मानना ​​है कि आपको ऐसा करने वाला एक फंक्शन बनाना चाहिए। बस संख्या को 1024 से भाग दें और परिणाम देखें। यदि इसकी अधिक संख्या 1024 है तो फिर से विभाजित करें।
इवान नेवोस्त्रेव

जवाबों:


319
function formatBytes($bytes, $precision = 2) { 
    $units = array('B', 'KB', 'MB', 'GB', 'TB'); 

    $bytes = max($bytes, 0); 
    $pow = floor(($bytes ? log($bytes) : 0) / log(1024)); 
    $pow = min($pow, count($units) - 1); 

    // Uncomment one of the following alternatives
    // $bytes /= pow(1024, $pow);
    // $bytes /= (1 << (10 * $pow)); 

    return round($bytes, $precision) . ' ' . $units[$pow]; 
} 

(से लिया php.net , कई अन्य उदाहरण वहाँ यह एक सबसे अच्छा की तरह हैं, लेकिन मैं :-)


8
यदि आप उपयोग करते हैं $bytes /= (1 << (10 * $pow))या पसंद करते हैं, तो मैं इसे बेहतर तरीके से पसंद कर सकता हूं। :-P
क्रिस जस्टर-यंग

5
वहां आप जाते हैं: डी (व्यक्तिगत रूप से, मुझे बिटवाइज़ अंकगणित पसंद नहीं है, क्योंकि यह समझना मुश्किल है कि क्या आप इसके लिए अभ्यस्त नहीं हैं ...)
लियो

3
@ जस्टिन ऐसा इसलिए है क्योंकि 9287695/1024/1024 वास्तव में 8,857 है :)
Mahn

30
वास्तव में, यह है KiB, MiB, GiBऔर TiBजब से तुम से विभाजित कर रहे हैं 1024। यदि आप 1000इसे से विभाजित करते हैं तो इसके बिना होगा i
डेविटर

8
Uncomment one of the following alternativesकुछ ऐसा था जिसे मैंने 5 मिनट तक नहीं देखा था ...
अर्निस जुरगा

211

यह क्रिस जस्टर-यंग का कार्यान्वयन है, जो मैंने कभी देखा है, php.net और एक सटीक तर्क के साथ संयुक्त रूप से देखा है।

function formatBytes($size, $precision = 2)
{
    $base = log($size, 1024);
    $suffixes = array('', 'K', 'M', 'G', 'T');   

    return round(pow(1024, $base - floor($base)), $precision) .' '. $suffixes[floor($base)];
}

echo formatBytes(24962496);
// 23.81M

echo formatBytes(24962496, 0);
// 24M

echo formatBytes(24962496, 4);
// 23.8061M

8
इसमें 2 त्रुटियां हैं - 1 से (कम से कम छोटी) फ़ाइलों का आकार जोड़ें - 0 के साथ काम नहीं कर (वापसी नान)
maazza

अच्छा है। क्या इस का एक संस्करण दूसरा तरीका है?
ल्यूक

3
एक lil सपना देख : $suffixes = array('B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'); मैं एक Yottabyte हार्ड ड्राइव चाहता हूँ! :-P
SpYk3HH

1
मुझे काम करने के लिए $ आकार को दोगुना करना पड़ा। heres ने मेरे लिए क्या काम किया: फ़ंक्शन प्रारूपबाइट्स ($ आकार, $ परिशुद्धता = 2) {$ आधार = लॉग (फ़्लोटवल ($ आकार)) / लॉग (1024); $ प्रत्यय = सरणी ('' ',' के ',' एम ',' जी ',' टी '); रिटर्न राउंड (पाओ (1024, $ बेस - फ्लोर ($ बेस)), $ परिशुद्धता)। $ प्रत्यय [मंजिल ($ आधार)]; }
क्रिस्टोफर ग्रे

formatBytes(259748192, 3)रिटर्न 259748192 MBजो सही नहीं है
Flip


15

यह कोहना का कार्यान्वयन है, आप इसका उपयोग कर सकते हैं:

public static function bytes($bytes, $force_unit = NULL, $format = NULL, $si = TRUE)
{
    // Format string
    $format = ($format === NULL) ? '%01.2f %s' : (string) $format;

    // IEC prefixes (binary)
    if ($si == FALSE OR strpos($force_unit, 'i') !== FALSE)
    {
        $units = array('B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB');
        $mod   = 1024;
    }
    // SI prefixes (decimal)
    else
    {
        $units = array('B', 'kB', 'MB', 'GB', 'TB', 'PB');
        $mod   = 1000;
    }

    // Determine unit to use
    if (($power = array_search((string) $force_unit, $units)) === FALSE)
    {
        $power = ($bytes > 0) ? floor(log($bytes, $mod)) : 0;
    }

    return sprintf($format, $bytes / pow($mod, $power), $units[$power]);
}

1024 और 1000 शक्ति के बीच एक विकल्प होने का उनका विचार अच्छा है। लेकिन यह कार्यान्वयन वास्तव में अजीब है। $force_unitऔर $siएक ही काम करने लगते हैं। आप इसमें "i" के साथ किसी भी स्ट्रिंग को पास कर सकते हैं $force_unit, क्योंकि वे स्थिति के लिए परीक्षण करते हैं। दशमलव स्वरूपण भी ओवरकिल है।
गस नेव्स

14

बस इसे kb के लिए 1024 से विभाजित करें, mb के लिए 1024 ^ 2 और GB के लिए 1024 ^ 3 है। इतना सरल है।


8

बस मेरा विकल्प, छोटा और साफ:

/**
 * @param int $bytes Number of bytes (eg. 25907)
 * @param int $precision [optional] Number of digits after the decimal point (eg. 1)
 * @return string Value converted with unit (eg. 25.3KB)
 */
function formatBytes($bytes, $precision = 2) {
    $unit = ["B", "KB", "MB", "GB"];
    $exp = floor(log($bytes, 1024)) | 0;
    return round($bytes / (pow(1024, $exp)), $precision).$unit[$exp];
}

या, अधिक बेवकूफ और प्रभावकारक:

function formatBytes($bytes, $precision = 2) {
    if ($bytes > pow(1024,3)) return round($bytes / pow(1024,3), $precision)."GB";
    else if ($bytes > pow(1024,2)) return round($bytes / pow(1024,2), $precision)."MB";
    else if ($bytes > 1024) return round($bytes / 1024, $precision)."KB";
    else return ($bytes)."B";
}

7

यदि आप एक छोटा कोड चाहते हैं तो इस फ़ंक्शन का उपयोग करें

bcdiv ()

$size = 11485760;
echo bcdiv($size, 1048576, 0); // return: 10

echo bcdiv($size, 1048576, 2); // return: 10,9

echo bcdiv($size, 1048576, 2); // return: 10,95

echo bcdiv($size, 1048576, 3); // return: 10,953

6

मुझे पता है कि इस सवाल का जवाब देने में थोड़ी देर हो सकती है लेकिन, अधिक डेटा किसी को मारने नहीं जा रहा है। यहाँ एक बहुत तेज़ कार्य है:

function format_filesize($B, $D=2){
    $S = 'BkMGTPEZY';
    $F = floor((strlen($B) - 1) / 3);
    return sprintf("%.{$D}f", $B/pow(1024, $F)).' '.@$S[$F].'B';
}

संपादित करें: मैंने कैमोमाइलकेस द्वारा प्रस्तावित फिक्स को शामिल करने के लिए अपनी पोस्ट अपडेट की:

function format_filesize($B, $D=2){
    $S = 'kMGTPEZY';
    $F = floor((strlen($B) - 1) / 3);
    return sprintf("%.{$D}f", $B/pow(1024, $F)).' '.@$S[$F-1].'B';
}

1
आपको $ B के छोटे मूल्यों के लिए एक डबल B (BB) मिलता है, क्योंकि आपके आस-पास का काम "$ S = 'kMGTPEZY' कर सकता है, और इसके बजाय" @ $ S [$ F] "करना" @ $ S [$ एफ -1] "।
कैमोमाइलकेस

@camomileCase दो साल और आधे बाद में - मैंने अपना जवाब अपडेट किया। धन्यवाद।
डेविड बेलांगेर

4

साधारण कार्य

function formatBytes($size, $precision = 0){
    $unit = ['Byte','KiB','MiB','GiB','TiB','PiB','EiB','ZiB','YiB'];

    for($i = 0; $size >= 1024 && $i < count($unit)-1; $i++){
        $size /= 1024;
    }

    return round($size, $precision).' '.$unit[$i];
}

echo formatBytes('1876144', 2);
//returns 1.79 MiB

3

लचीला समाधान:

function size($size, array $options=null) {

    $o = [
        'binary' => false,
        'decimalPlaces' => 2,
        'decimalSeparator' => '.',
        'thausandsSeparator' => '',
        'maxThreshold' => false, // or thresholds key
        'suffix' => [
            'thresholds' => ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'],
            'decimal' => ' {threshold}B',
            'binary' => ' {threshold}iB',
            'bytes' => ' B'
        ]
    ];

    if ($options !== null)
        $o = array_replace_recursive($o, $options);

    $base = $o['binary'] ? 1024 : 1000;
    $exp = $size ? floor(log($size) / log($base)) : 0;

    if (($o['maxThreshold'] !== false) &&
        ($o['maxThreshold'] < $exp)
    )
        $exp = $o['maxThreshold'];

    return !$exp
        ? (round($size) . $o['suffix']['bytes'])
        : (
            number_format(
                $size / pow($base, $exp),
                $o['decimalPlaces'],
                $o['decimalSeparator'],
                $o['thausandsSeparator']
            ) .
            str_replace(
                '{threshold}',
                $o['suffix']['thresholds'][$exp],
                $o['suffix'][$o['binary'] ? 'binary' : 'decimal']
            )
        );
}

var_dump(size(disk_free_space('/')));
// string(8) "14.63 GB"
var_dump(size(disk_free_space('/'), ['binary' => true]));
// string(9) "13.63 GiB"
var_dump(size(disk_free_space('/'), ['maxThreshold' => 2]));
// string(11) "14631.90 MB"
var_dump(size(disk_free_space('/'), ['binary' => true, 'maxThreshold' => 2]));
// string(12) "13954.07 MiB"

2

मैं निम्नलिखित समारोह के साथ सफल रहा,

    function format_size($size) {
        $mod = 1024;
        $units = explode(' ','B KB MB GB TB PB');
        for ($i = 0; $size > $mod; $i++) {
            $size /= $mod;
        }
        return round($size, 2) . ' ' . $units[$i];
    }

2
खबरदार: K केल्विन के लिए है और k किलो के लिए है।
ZeWaren

2

मेरा दृष्टिकोण

    function file_format_size($bytes, $decimals = 2) {
  $unit_list = array('B', 'KB', 'MB', 'GB', 'PB');

  if ($bytes == 0) {
    return $bytes . ' ' . $unit_list[0];
  }

  $unit_count = count($unit_list);
  for ($i = $unit_count - 1; $i >= 0; $i--) {
    $power = $i * 10;
    if (($bytes >> $power) >= 1)
      return round($bytes / (1 << $power), $decimals) . ' ' . $unit_list[$i];
  }
}

2

मुझे नहीं पता कि आपको इसे दूसरों की तरह जटिल क्यों बनाना चाहिए।

निम्नलिखित कोड समझने के लिए बहुत सरल है और लॉग समाधान का उपयोग करने वाले अन्य समाधानों की तुलना में लगभग 25% तेज है (विभिन्न मापदंडों के साथ फ़ंक्शन 20 Mio. times कहा जाता है)

function formatBytes($bytes, $precision = 2) {
    $units = ['Byte', 'Kilobyte', 'Megabyte', 'Gigabyte', 'Terabyte'];
    $i = 0;

    while($bytes > 1024) {
        $bytes /= 1024;
        $i++;
    }
    return round($bytes, $precision) . ' ' . $units[$i];
}

2

मैंने इसे सभी इनपुट को बाइट में परिवर्तित किया और इसलिए आवश्यक किसी भी आउटपुट में परिवर्तित किया। इसके अलावा, मैंने आधार 1000 या 1024 प्राप्त करने के लिए एक अपरिवर्तनीय फ़ंक्शन का उपयोग किया, लेकिन लोकप्रिय प्रकार ('i' के बिना, MiB के बजाय MB की तरह) का उपयोग करने का निर्णय लेने के लिए इसे फ्लेक्स छोड़ दिया।

    public function converte_binario($size=0,$format_in='B',$format_out='MB',$force_in_1024=false,$force_out_1024=false,$precisao=5,$return_format=true,$decimal=',',$centena=''){
    $out = false;

    if( (is_numeric($size)) && ($size>0)){
        $in_data = $this->converte_binario_aux($format_in,$force_in_1024);
        $out_data = $this->converte_binario_aux($format_out,$force_out_1024);

        // se formato de entrada e saída foram encontrados
        if( ((isset($in_data['sucesso'])) && ($in_data['sucesso']==true)) && ((isset($out_data['sucesso'])) && ($out_data['sucesso']==true))){
            // converte formato de entrada para bytes.
            $size_bytes_in = $size * (pow($in_data['base'], $in_data['pot']));
            $size_byte_out = (pow($out_data['base'], $out_data['pot']));
            // transforma bytes na unidade de destino
            $out = number_format($size_bytes_in / $size_byte_out,$precisao,$decimal,$centena);
            if($return_format){
                $out .= $format_out;
            }
        }
    }
    return $out;
}

public function converte_binario_aux($format=false,$force_1024=false){
    $out = [];
    $out['sucesso'] = false;
    $out['base'] = 0;
    $out['pot'] = 0;
    if((is_string($format) && (strlen($format)>0))){
        $format = trim(strtolower($format));
        $units_1000 = ['b','kb' ,'mb' ,'gb' ,'tb' ,'pb' ,'eb' ,'zb' ,'yb' ];
        $units_1024 = ['b','kib','mib','gib','tib','pib','eib','zib','yib'];
        $pot = array_search($format,$units_1000);
        if( (is_numeric($pot)) && ($pot>=0)){
            $out['pot'] = $pot;
            $out['base'] = 1000;
            $out['sucesso'] = true;
        }
        else{
            $pot = array_search($format,$units_1024);
            if( (is_numeric($pot)) && ($pot>=0)){
                $out['pot'] = $pot;
                $out['base'] = 1024;
                $out['sucesso'] = true;
            }
        }
        if($force_1024){
            $out['base'] = 1024;
        }
    }
    return $out;
}

1

इसे इस्तेमाल करे ;)

function bytesToSize($bytes) {
                $sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
                if ($bytes == 0) return 'n/a';
                $i = intval(floor(log($bytes) / log(1024)));
                if ($i == 0) return $bytes . ' ' . $sizes[$i]; 
                return round(($bytes / pow(1024, $i)),1,PHP_ROUND_HALF_UP). ' ' . $sizes[$i];
            }
echo bytesToSize(10000050300);

1
function changeType($size, $type, $end){
    $arr = ['B', 'KB', 'MB', 'GB', 'TB'];
    $tSayi = array_search($type, $arr);
    $eSayi = array_search($end, $arr);
    $pow = $eSayi - $tSayi;
    return $size * pow(1024 * $pow) . ' ' . $end;
}

echo changeType(500, 'B', 'KB');

1
function convertToReadableSize($size)
{
  $base = log($size) / log(1024);
  $suffix = array("B", "KB", "MB", "GB", "TB");
  $f_base = floor($base);
  return round(pow(1024, $base - floor($base)), 1) . $suffix[$f_base];
}

बस फ़ंक्शन को कॉल करें

echo convertToReadableSize(1024); // Outputs '1KB'
echo convertToReadableSize(1024 * 1024); // Outputs '1MB'

1

यह अंतिम PHP के साथ काम करता है

function formatBytes($bytes, $precision = 2) { 
    $units = array('B', 'KB', 'MB', 'GB', 'TB'); 

    $bytes = max($bytes, 0); 
    $pow = floor(($bytes ? log($bytes) : 0) / log(1024)); 
    $pow = min($pow, count($units) - 1); 

    $bytes /= pow(1024, $pow); 

    return round($bytes, $precision) . ' ' . $units[$pow]; 
} 

यह सब वहाँ किया गया था PHP.net से एक उदाहरण की एक ही सटीक प्रतिलिपि है जो 2010 में मुख्य उत्तरदाता द्वारा केवल 8 साल बाद कर रहा था।
जेकगॉल्ड

1

थोड़ा बासी होने पर, यह लाइब्रेरी एक परीक्षित और मजबूत रूपांतरण एपीआई प्रदान करती है:

https://github.com/gabrielelana/byte-units

एक बार स्थापित:

\ByteUnits\Binary::bytes(1024)->format();

// Output: "1.00KiB"

और दूसरी दिशा में बदलने के लिए:

\ByteUnits\Binary::parse('1KiB')->numberOfBytes();

// Output: "1024"

बुनियादी रूपांतरण से परे, इसके अलावा, घटाव, तुलना, आदि के लिए तरीके प्रदान करता है।

मैं इस पुस्तकालय से संबद्ध नहीं हूं।


0
function byte_format($size) {
    $bytes = array( ' KB', ' MB', ' GB', ' TB' );
    foreach ($bytes as $val) {
        if (1024 <= $size) {
            $size = $size / 1024;
            continue;
        }
        break;
    }
    return round( $size, 1 ) . $val;
}

0

यहाँ Drupal format_size फ़ंक्शन का सरलीकृत कार्यान्वयन है :

/**
 * Generates a string representation for the given byte count.
 *
 * @param $size
 *   A size in bytes.
 *
 * @return
 *   A string representation of the size.
 */
function format_size($size) {
  if ($size < 1024) {
    return $size . ' B';
  }
  else {
    $size = $size / 1024;
    $units = ['KB', 'MB', 'GB', 'TB'];
    foreach ($units as $unit) {
      if (round($size, 2) >= 1024) {
        $size = $size / 1024;
      }
      else {
        break;
      }
    }
    return round($size, 2) . ' ' . $unit;
  }
}

0

यह थोड़ी देर का है लेकिन स्वीकृत उत्तर का थोड़ा तेज संस्करण नीचे है:

function formatBytes($bytes, $precision)
{
    $unit_list = array
    (
        'B',
        'KB',
        'MB',
        'GB',
        'TB',
    );

    $bytes = max($bytes, 0);
    $index = floor(log($bytes, 2) / 10);
    $index = min($index, count($unit_list) - 1);
    $bytes /= pow(1024, $index);

    return round($bytes, $precision) . ' ' . $unit_list[$index];
}

दो लॉग-ई ऑपरेशन्स के बजाय एक लॉग -2 ऑपरेशन करने के कारण यह अधिक कुशल है।

यह वास्तव में नीचे अधिक स्पष्ट समाधान करने के लिए तेजी से है, हालांकि:

function formatBytes($bytes, $precision)
{
    $unit_list = array
    (
        'B',
        'KB',
        'MB',
        'GB',
        'TB',
    );

    $index_max = count($unit_list) - 1;
    $bytes = max($bytes, 0);

    for ($index = 0; $bytes >= 1024 && $index < $index_max; $index++)
    {
        $bytes /= 1024;
    }

    return round($bytes, $precision) . ' ' . $unit_list[$index];
}

यह इसलिए है क्योंकि सूचकांक की गणना उसी समय की जाती है जब उपयुक्त इकाई में बाइट्स की संख्या का मान होता है। इसने निष्पादन समय में लगभग 35% (55% की गति वृद्धि) में कटौती की।


0

एक और गाढ़ा क्रियान्वयन जो कि आधार 1024 (बाइनरी) या बेस 1000 (दशमलव) में अनुवाद कर सकता है और साथ ही साथ यह bc लाइब्रेरी के उपयोग के कारण अविश्वसनीय रूप से बड़ी संख्या में काम करता है:

function renderSize($byte,$precision=2,$mibi=true)
{
    $base = (string)($mibi?1024:1000);
    $labels = array('K','M','G','T','P','E','Z','Y');
    for($i=8;$i>=1;$i--)
        if(bccomp($byte,bcpow($base, $i))>=0)
            return bcdiv($byte,bcpow($base, $i), $precision).' '.$labels[$i-1].($mibi?'iB':'B');
    return $byte.' Byte';
}

बस थोड़ा सा ध्यान दें; bcpow()TypeError अपवाद फेंक देंगे यदि $baseऔर $iस्ट्रिंग मान नहीं हैं। PHP संस्करण 7.0.11 पर परीक्षण किया गया।
डेविड कैरी

धन्यवाद! मैंने स्ट्रिंग कॉस्टर को जोड़ा और एक ऑफसेट बग तय किया :)
क्रिश्चियन

0

मुझे लगा कि मैं दो सबमिटर कोड (जॉन हिमेलमैन के कोड का उपयोग करके, जो इस धागे में है, और यूजीन कुजमेनको के कोड का उपयोग करके) जोड़ूंगा जो मैं उपयोग कर रहा हूं।

function swissConverter($value, $format = true, $precision = 2) {
    //Below converts value into bytes depending on input (specify mb, for 
    //example)
    $bytes = preg_replace_callback('/^\s*(\d+)\s*(?:([kmgt]?)b?)?\s*$/i', 
    function ($m) {
        switch (strtolower($m[2])) {
          case 't': $m[1] *= 1024;
          case 'g': $m[1] *= 1024;
          case 'm': $m[1] *= 1024;
          case 'k': $m[1] *= 1024;
        }
        return $m[1];
        }, $value);
    if(is_numeric($bytes)) {
        if($format === true) {
            //Below converts bytes into proper formatting (human readable 
            //basically)
            $base = log($bytes, 1024);
            $suffixes = array('', 'KB', 'MB', 'GB', 'TB');   

            return round(pow(1024, $base - floor($base)), $precision) .' '. 
                     $suffixes[floor($base)];
        } else {
            return $bytes;
        }
    } else {
        return NULL; //Change to prefered response
    }
}

यह यूजीन कोड को $valueबाइट्स में प्रारूपित करने के लिए उपयोग करता है (मैं अपने डेटा को एमबी में रखता हूं, इसलिए यह मेरे डेटा को परिवर्तित करता है: 10485760 MBमें 10995116277760) - यह जॉन के कोड का उपयोग करके इसे उचित प्रदर्शन मान में परिवर्तित करता है ( 10995116277760में10 TB ) ।

मैंने इसे वास्तव में मददगार पाया है - इसलिए दो सबमिटर के लिए मेरा धन्यवाद!


0

मानव फ़ाइल आकार प्राप्त करने के लिए अत्यंत सरल कार्य।

मूल स्रोत: http://php.net/manual/de/function.filesize.php#106569

कॉपी / पेस्ट कोड:

<?php
function human_filesize($bytes, $decimals = 2) {
  $sz = 'BKMGTP';
  $factor = floor((strlen($bytes) - 1) / 3);
  return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . @$sz[$factor];
}
?>

0

मैंने अपना स्वयं का फ़ंक्शन विकसित किया है जो मानव पठनीय स्मृति आकार को विभिन्न आकारों में परिवर्तित करता है।

function convertMemorySize($strval, string $to_unit = 'b')
{
    $strval    = strtolower(str_replace(' ', '', $strval));
    $val       = floatval($strval);
    $to_unit   = strtolower(trim($to_unit))[0];
    $from_unit = str_replace($val, '', $strval);
    $from_unit = empty($from_unit) ? 'b' : trim($from_unit)[0];
    $units     = 'kmgtph';  // (k)ilobyte, (m)egabyte, (g)igabyte and so on...


    // Convert to bytes
    if ($from_unit !== 'b')
        $val *= 1024 ** (strpos($units, $from_unit) + 1);


    // Convert to unit
    if ($to_unit !== 'b')
        $val /= 1024 ** (strpos($units, $to_unit) + 1);


    return $val;
}


convertMemorySize('1024Kb', 'Mb');  // 1
convertMemorySize('1024', 'k')      // 1
convertMemorySize('5.2Mb', 'b')     // 5452595.2
convertMemorySize('10 kilobytes', 'bytes') // 10240
convertMemorySize(2048, 'k')        // By default convert from bytes, result is 2

यह फ़ंक्शन "मेगाबाइट, एमबी, एमबी, एमबी, एमबी, किलोबाइट, के, केबी, बी, टेराबाइट, टी ...." जैसे किसी भी स्मृति आकार के संक्षिप्त नाम को स्वीकार करता है, इसलिए यह टाइपो सुरक्षित है।


0

लियो के जवाब के आधार पर , जोड़ें

  • नकारात्मक के लिए समर्थन
  • समर्थन 0 <मूल्य <1 (पूर्व: 0.2, लॉग का कारण होगा (मान) = नकारात्मक संख्या)

यदि आप मेगा के लिए अधिकतम इकाई चाहते हैं, तो बदल दें $units = explode(' ', ' K M');


function formatUnit($value, $precision = 2) {
    $units = explode(' ', ' K M G T P E Z Y');

    if ($value < 0) {
        return '-' . formatUnit(abs($value));
    }

    if ($value < 1) {
        return $value . $units[0];
    }

    $power = min(
        floor(log($value, 1024)),
        count($units) - 1
    );

    return round($value / pow(1024, $power), $precision) . $units[$power];
}
हमारी साइट का प्रयोग करके, आप स्वीकार करते हैं कि आपने हमारी Cookie Policy और निजता नीति को पढ़ और समझा लिया है।
Licensed under cc by-sa 3.0 with attribution required.