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-10 03:26 am (UTC)(link)
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.