darxus: (Default)
darxus ([personal profile] darxus) wrote2009-09-09 04:38 pm
Entry tags:

[geek] How apache 2's autoindex converts bytes to kilobytes and megabytes.

This was tedious to figure out, so hopefully I can spare someone else. In perl:

if ($sizeunit eq 'K') {
  $realsize = round($realsize/1024);
} elsif ($sizeunit eq 'M') {
  $realsize = round($realsize/1024/1024);
}

sub round {
  my($number) = shift;
  my $left = (split('\.',$number))[0];
  if (length($left) <= 1) {
    return int( $number * 10 + .5 )/10;
  } else {
    return int( $number + .5 );
  }
}


I'm convinced there is no simpler way (I read the whole sprintf man page at least twice).

I'm writing a monitoring script that checks the sizes of files on a web server. So I figured I should do a little random validation that apache is reporting the same file size that I'm getting from length($content). So I needed to convert length($content) to the same form I get from apache.
cos: (Default)

Re: real rounding with sprintf

[personal profile] cos 2009-09-09 10:33 pm (UTC)(link)
Ahh, I see what you're saying. Something like this?

$size /= 1024;
$pr = $size<9.5 ? 1 : 0;
$round = sprintf("%.${pr}", $size);

Re: real rounding with sprintf

[identity profile] darxus.livejournal.com 2009-09-09 11:42 pm (UTC)(link)
Looks likely to work.