Darxus

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

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

Previous Entry Add to Memories Share this! Next Entry
2009-09-29
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.
  • There's no way to include such basic math functions as Round() or use the modulo operator?
    • Perl has no round(). The faq entry tells you how to write it. I'm not great with modulo, so it's not obvious to me how it would be useful.
  • how to do it with sprintf

    if ($sizeunit eq 'K') {
      $realsize = sprintf("%d",$realsize/1024 +.5);
    } elsif ($sizeunit eq 'M') {
      $realsize = sprintf("%d",$realsize/1024/1024 +.5);
    }
    
  • real rounding with sprintf

    Oops, I forgot the floating point conversation always does real rounding, so another way is:

    $rounded = sprintf("%.0f", $number/1024);
    • Re: real rounding with sprintf

      You skipped the variable precision.
      • Re: real rounding with sprintf

        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

      Hmm... I can't remember where the discussion was (aside from "somebody else's journal), but I got chided semi-recently for suggesting sprintf as a method of rounding. The other person said it was slow and error-prone. I can't recall if I asked for a reference for this claim. I'll try to remember where this discussion took place and see if there was anything to substantiate the other person's claim.
      • Re: real rounding with sprintf

        You could do $rounded = int($num+.5) but he mentioned sprintf specifically. For variable precision sprintf is easier, and I highly doubt rounding performance is a big issue in this kind of application.
Powered by LiveJournal.com