Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

How do I convert one number storing the size of a file in bytes to a representation in Kbytes or Mbytes?

Replies are listed 'Best First'.
Re: file size representation
by merlyn (Sage) on Jul 16, 2001 at 23:33 UTC
    I prefer rounding to the nearest K, as in:
    my $k_size = sprintf "%.0fK", $size / 1024;
    Or perhaps always rounding up, so that we never show a small file as "0K", which seems intuitively to mean an "empty file" for me:
    my $k_size = sprintf "%dK", ($size + 1023) / 1024;

    -- Randal L. Schwartz, Perl hacker

Re: file size representation
by bikeNomad (Priest) on Jul 16, 2001 at 21:44 UTC
    divide it by 1024 and add 'K'

    or divide it by 1024*1024 and add 'M'

Re: file size representation
by HyperZonk (Friar) on Jul 16, 2001 at 22:28 UTC
    A very full implementation might be:
    sub best_size { my $r = shift; ($r > (1024 * 1024)) ? return sprintf("%1.3f", $r/(1024*1024)) . 'M +B' : ($r > 1024) ? return sprintf("%1.3f", $r/1024) . 'K +B' : return $r . 'B'; }

    This will return a string with the "most appropriate" suffix. Modify to suit your purposes, such as different precisions, or changing to the next suffix before actually reaching 1KB, 1MB, etc.
Re: file size representation
by $code or die (Deacon) on Jul 16, 2001 at 21:50 UTC
    Very crude, but you can expand on it. It is basic math.
    sub toKbytes { my $bytes = shift; return $bytes / 1024; } sub toMbytes { my $bytes = shift; return $bytes / (1024 * 1024); }
    Then you can do:

    print toMbytes(1048576), "\n";
    print toKbytes(1048576), "\n";

    You'll also want to read up on sprintf or printf if you want to round off the return values.

    Error: Keyboard not attached. Press F1 to continue.