PERL Round Function

Hey all your PERL junkies like me, I have a present for you. Anyone that has done any coding at all other PERL will know (and miss) the round function that most other languages have built in. For those that may not know, the round function lets you do just that, round a number to the specified digit. So, instead of having to use 3.14159265 as an answer for a particular equation, you could round it to 3.14. Nice, huh?

Well, here is a neato little round function that you can drop into your PERL scripts and call to actually round numbers instead of cutting them off with ceil or cut. Check it out:

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

There you go!

**Update**
Thanks to Thierry H. for adding a little mod to the round function allowing you to specify the number of decimals to print. Here is the modified function:

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

You would call it by giving not only the number to round, but how many numbers to show on the right side of the decimal. It will look like so:

$result = round(123.4567,3);

This should return 123.457 (the 6 in the third slot gets rounded to 7). There ya go, thanks for the mod Thierry! You can check out Thierry’s site here.