http://qs321.pair.com?node_id=245110

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

how can i round a variable (lets say $price = 418.00 ;) to the nearest 10 ie '420.00'

Replies are listed 'Best First'.
Re: rounding to nearest
by dakkar (Hermit) on Mar 22, 2003 at 09:18 UTC
    $nearest=10; $price=int(($price+$nearest/2)/$nearest)*$nearest;

    This is parametric on the "granularity"

    UPDATE: and it also works if $nearest is less than 1 (say you want to round to the nearest 0.5)

    -- 
            dakkar - Mobilis in mobile
    
Re: rounding to nearest
by rob_au (Abbot) on Mar 22, 2003 at 09:21 UTC
    How about the following?

    sub round { my ( $price, $round ) = @_; return int(( $price / $round ) + 0.5 ) * $round; } print round( 418, 10 ), "\n";

    The round subroutine takes two parameters, the number to be rounded and the nearest value to which you want it to be rounded to.

     

    perl -le 'print+unpack("N",pack("B32","00000000000000000000001001000001"))'

Re: rounding to nearest
by mojotoad (Monsignor) on Mar 22, 2003 at 15:40 UTC
    use Math::Round qw(nearest); $quote = 418.00; $price = nearest(10, $quote);

    I don't know if it's important, but this implementation deals properly with negative numbers. From Math::Round:

    sub nearest { my ($targ, @inputs) = @_; my @res = (); my $x; $targ = abs($targ) if $targ < 0; foreach $x (@inputs) { if ($x >= 0) { push @res, $targ * int(($x + $half * $targ) / $targ); } else { push @res, $targ * POSIX::ceil(($x - $half * $targ) / $targ); } } return (wantarray) ? @res : $res[0]; }

    Cheers,
    Matt

Re: rounding to nearest
by dws (Chancellor) on Mar 22, 2003 at 10:15 UTC
    how can i round a variable (lets say $price = 418.00 ;) to the nearest 10 ie '420.00'

    Be aware that in certain situations it's considered bad form to pretend to maintain precision at the hundredth level when you've just rounded the nearest 10. You might want to clarify whether '418.00' rounds to '420.00' or '420'.