Sunday, March 22, 2009

PERL round function

Following is the round function in PERL, which you can put into your script and actually call to round numbers instead of cutting them with ceil or cut.

In the following round function, you can specify the number to round and the number of digits to show after the decimal.

sub round {
my $number = shift || 0;
my $dec = 10 ** (shift || 0);
return int( $dec * $number + .5 * ($number <=> 0)) / $dec;
}

$result = round(123.4567,3);

it would return 123.457




2 comments:

Unknown said...
This comment has been removed by the author.
Demon said...

Perl is the best scripting language for Text processing and handle regex. I have posted few articles related to those at my blog

http://icfun.blogspot.com/search/label/perl

Also Perl's Cpan has lots of support that I don't even need to think extra while developing project. I didn't find such help on other programming language except Java and .NET