SPUG:strange rounding problems

Peter Darley pdarley at kinesis-cem.com
Thu Jan 30 16:09:33 CST 2003

	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).
Peter Darley

-----Original Message-----
From: spug-list-admin at mail.pm.org [mailto:spug-list-admin at mail.pm.org]On
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

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)
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

More information about the spug-list mailing list