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 | [reply] [d/l] [select] |
| [reply] |
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. | [reply] [d/l] |
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. | [reply] [d/l] |