SPUG:strange rounding problems

Alan alan at ufies.org
Thu Jan 30 15:54:53 CST 2003

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

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.



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)

More information about the spug-list mailing list