# SPUG:strange rounding problems

Thu Jan 30 16:24:01 CST 2003

```Odd rounds up, even rounds down.
e.g.:

11.5 -> 12
12.5 -> 12
13.5 -> 14
14.5 -> 14
15.5 -> 15

This prevents skewing in favor of up.

do not use int( \$Value+.5) unless you know that \$Value >= 0 !

>>> "Peter Darley" <pdarley at kinesis-cem.com> 01/30/03 05:09PM >>>
Folks,
I've had problems with this as well, and eventually abandoned
sprintf all
together.  It's always kind of bugged me tho.  The best solution for
rounding I came up with is int(\$Value+.5).
Thanks,
Peter Darley

-----Original Message-----
Behalf Of Alan
Sent: Thursday, January 30, 2003 1:55 PM
To: spug-list at pm.org
Subject: SPUG:strange rounding problems

This may be a very silly question, but I figured I'd ask the local
monks...

The perl cookbook recommends using sprintf to do rounding, or write
your
own.  The rounding that I need is pretty simple, so I figured that
just
rounding off via sprintf would not require me to write my own routine.

First I have to clarify.  When I learnt about rounding, it was you
round
down if it is < 5, and round up if it is >= 5.  IE: rounding (to whole
numbers) 12.4 gives you 12, and 12.7 gives you 13.

Using the code from the cookbook I found with the following program

\$a = 12.30;
\$b = sprintf("%.0f", \$a);
print "Unrounded: \$a\nRounded: \$b\n";

I got the following results:

Unrounded: 12.3
Rounded: 12

Fine so far.  Changing \$a to 12.7 gives:

Unrounded: 12.7
Rounded: 13

Ok so far.  But how about 12.5:

Unrounded: 12.5
Rounded: 12

Not quite right.  But 12.5000000001:

Unrounded: 12.5000000001
Rounded: 13

Is this a bug or is this me now knowing how to round properly?  I've
got
my own routine that rounds "properly", but I'm interested in knowing
why
there is this strange rounding behaviour.

TIA

alan

--
Alan <alan at ufies.org> - http://arcterex.net
---------------------------------------------------------------------
"The only thing that experience teaches us is that experience teaches
us nothing.	        -- Andre Maurois (Emile Herzog)
_____________________________________________________________
Seattle Perl Users Group Mailing List
POST TO: spug-list at mail.pm.org
ACCOUNT CONFIG: http://mail.pm.org/mailman/listinfo/spug-list
MEETINGS: 3rd Tuesdays, U-District, Seattle WA
WEB PAGE: www.seattleperl.org

_____________________________________________________________
Seattle Perl Users Group Mailing List
POST TO: spug-list at mail.pm.org
ACCOUNT CONFIG: http://mail.pm.org/mailman/listinfo/spug-list
MEETINGS: 3rd Tuesdays, U-District, Seattle WA
WEB PAGE: www.seattleperl.org

```