Warning: Undefined array key "search_mode" in /home/bakers/html/search.php on line 27

Warning: Undefined array key "include_body" in /home/bakers/html/search.php on line 28

Warning: Undefined array key 1318 in /home/bakers/html/search.php on line 247

Warning: Undefined variable $search_results in /home/bakers/html/search.php on line 257

Warning: Undefined variable $start in /home/bakers/html/search.php on line 261

Warning: Undefined variable $message in /home/bakers/html/search.php on line 63

Warning: Undefined variable $output in /home/bakers/html/search.php on line 65
Perturb.org - interesting technology related things from around the internet

Showing entries with tag "round".

Found 1 entries

Perl: Rounding a number

If you need to round a number in Perl you can use the POSIX method round(). If for some reason you don't want to use the POSIX method I wrote a pure Perl version of round() that is pretty fast.

use POSIX;

my $num = 3.14156;

print(POSIX::round($num)); # 3
print(round($num));        # 3
sub round {
    my $num = shift();
    my $ret;

    if ($num < 0) {
        $ret = int($num - 0.5);
    } else {
        $ret = int($num + 0.5);
    }

    return $ret;
}

Along with round, sometimes you want "round to the nearest X", which I also implemented:

sub nearest {
    my ($num, $nearest) = @_;

    my $div = $num / $nearest;
    my $ret = round($div) * $nearest;

    return $ret;
}
Leave A Reply