in reply to Re: Rounding off numbers
in thread Rounding off numbers

(2*4.5+1)/2=5 (2*5.5+1)/2=6

so I tried:

(2*int(4.5)+1)/2=4.5 (2*int(5.5)+1)/2=5.5

so then I tried:

int(2*4.5+1)/2=5 int(2*5.5+1)/2=6

how's that equation and reasoning again? please verify, thanks. and needing a standard rounding algorithm. I am unsure now what's really correct that you've given.

Replies are listed 'Best First'.
Re^3: Rounding off numbers
by Athanasius (Archbishop) on Sep 13, 2014 at 09:34 UTC

    Hello jmichae3, and welcome to the Monastery!

    As swampyankee said, int($x + 0.5) correctly rounds $x to an integer, provided that $x is non-negative.

    So, for example, if you have 2 * 4.5 and want to make sure this comes out to 9, use:

    19:27 >perl -wE "my $x = 2 * 4.5; my $y = int($x + 0.5); say $y;" 9 19:28 >

    This is useful, because for some values (and on some machines), a calculation like 2 * 4.5 might come out as 8.99999999998. But with the formula: add 0.5 and truncate, that’s OK now:

    19:28 >perl -wE "my $x = 8.99999999998; my $y = int($x + 0.5); say $y; +" 9 19:30 >

    Hope that helps,

    Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,