in reply to Rounding off numbers

Or, to avoid sprintf, you could use:

$rounded = int($unrounded + 0.5);

There are actually defined standards for rounding; to be absolutely pedantic, numbers which are exact odd multiples of ½ (i.e., (2n + 1)⁄/2) should round to the nearest odd number, so 4.5 and 5.5 should both round to 5


added in edit

salva's post reminded me that my fragment will only work for positive values of $unrounded. For negative values, one would have to subtract 0.5

emc

"Being forced to write comments actually improves code, because it is easier to fix a crock than to explain it. "
—G. Steele

Replies are listed 'Best First'.
Re^2: Rounding off numbers
by Limbic~Region (Chancellor) on Apr 20, 2006 at 16:46 UTC
    swampyankee,
    There are actually defined standards for rounding; to be absolutely pedantic, numbers which are...

    Really? Where? I am not saying that because I don't believe you but because I am only familiar with rounding algorithms - not any standards. Do you have any reference material?

    I would have thought any standard would have been referenced in this rounding algorithm article or in the Wikipedia entry.

    Cheers - L~R

      Try this NIST pdf (although I seem to have reversed their rounding rules, which are "round to even" from the ones I remembered which were "round to odd". Ah, daily my memory more and more remembers a steel sieve).

      emc

      "Being forced to write comments actually improves code, because it is easier to fix a crock than to explain it. "
      —G. Steele
        That's not the maths I learnt at school. It's not very PC either, being unfair to odd numbers :-)
Re^2: Rounding off numbers
by jmichae3 (Initiate) on Sep 13, 2014 at 08:51 UTC
    (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.

      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,