in reply to rounding to nearest integer

There's a Q&A on exactly this here, but my old favourite is $rounded = int($number + 0.5); trashed below - doh! :).

Cheers,Ben.

Replies are listed 'Best First'.
•Re: Re: rounding to nearest integer
by merlyn (Sage) on May 11, 2003 at 11:55 UTC

      I supposed you could get the int() method to work on negatives by using abs() and some arithmetic with it.

      if ( $value < 0 ) { $rounded = ( int( abs($value) + 0.5) ); $rounded = $rounded - ( $rounded * 2 ); } else { $rounded = int($value + 0.5) }

      or something...

      Seems more complicated than sprintf() =)

      --
      Allolex

      Update: Added closing bracket. (2003-05-15 19:27:26 CEST)

Re^2: rounding to nearest integer (rounding bias)
by Aristotle (Chancellor) on May 11, 2003 at 11:41 UTC
    Note that sprintf will round values exactly halfway between two numbers (0.5 + int $X) up for odd and down for even numbers to avoid a bias toward rounding up.

    Makeshifts last the longest.

      I've heard that proposed many times, but I think it's a fallacy. Should you alternate between rounding N.0 up and down also? N.5 needs to be rounded up, and -N.5 needs to be rounded down.

      For any integer N, for all reals in the range [ N, N+1 ), that is, including N but not quite including N+1, then N+0.5 is in the upper half of the range closest to N+1, while anything less is in the lower half of the range closest to N.

      --
      [ e d @ h a l l e y . c c ]

        You only think it's a fallacy. I wrote some code to prove that it's true at counter-intuitive sprintf behaviour. Of special interest is merlyn's reply. At least now I understand why it is so, even if I still think the results are peculiar.

        _____________________________________________
        Come to YAPC::Europe 2003 in Paris, 23-25 July 2003.