Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I have a number that will be composed of some whole numbers and a decimal. How can I round or strip the decimals from the numer? Example: 872.56 should ideally be rounded to 873, but I'd be happy to even have 872 left. I've tried the below code but it doesn't work:
$quantity=~s/.(\d+)//;
I thought that this would remove everything to the right of the decimal point.

Replies are listed 'Best First'.
Re: Decimal Removal
by gumby (Scribe) on Jun 19, 2002 at 13:37 UTC
    The floor function is basically int() and therefore ceiling is int()+1. But as perlfunc says '...sprintf, printf, or the POSIX::floor and POSIX::ceil functions will serve you better than will int()'.
Re: Decimal Removal
by Sifmole (Chaplain) on Jun 19, 2002 at 13:36 UTC
    You need to "escape" your decimal and it is probably a good idea to anchor it to the end of the string if possible ("$")
    s/\.(\d+)$//;
    An unescaped "." is a meta-character not an actual ".".
      Also, unless you are going to use the stripped digits there is no reason to capture them with the  ()

      --

      flounder

        The poster implied they were because they were looking to do some rounding, as well they were capturing in the posted example. I was not trying to rewrite the posters code, just correct the things that were causing problems and improve where it didn't change the meaning.

        But yes you are right that if the poster does not intend to use the stripped digits then there is no reason to capture them with the parens.

(jeffa) Re: Decimal Removal
by jeffa (Bishop) on Jun 19, 2002 at 13:37 UTC
Re: Decimal Removal
by jmcnamara (Monsignor) on Jun 19, 2002 at 13:40 UTC

    One more method (rounds down):     $int = sprintf "%d", $num;

    Or this (rounds up for > .5):     $int = int $num + $num =~ /\.[5-9]/;

    --
    John.

      Or, to round to the nearest integer:
      $int = sprintf "%d", ( $num + 0.5 ) ;

      _______________
      D a m n D i r t y A p e
      Home Node | Email
Re: Decimal Removal
by Abigail-II (Bishop) on Jun 19, 2002 at 15:43 UTC
    Rounding to the nearest integer ought to be done with sprintf:
    my $rounded = sprintf "%.0f" => $not_rounded;

    Abigail