Perl help

Kevin D. Clark kclark at CetaceanNetworks.com
Tue Jul 22 17:13:03 EDT 2003


Cole Tuininga <colet at code-energy.com> writes:

> Got a perl question for y'all.  I rarely have to do anything with perl,

That's too bad.  

> and I'm sure perl has a good reason for behaving like the following, but
> heck if I can figure it out.
> 
> The perl cookbook suggestions using sprintf for rounding floats.  This
> seemingly works fine:
> 
> egon at trogdor:~$ perl -e 'print sprintf( "%.2f\n", 0.562 )'
> 0.56
> egon at trogdor: perl -e 'print sprintf( "%.2f\n", 0.567 )'
> 0.57
> 
> However, I'm extremely confused by the following:
> 
> egon at trogdor:~$ perl -e 'print sprintf( "%.2f\n", 0.565 )'
> 0.56
> 
> Can anybody explain why this is not rounding up?  Thanks in advance...

The problem is is that you (The Human) see 0.565 as being an exact
floating point number.  Perl, running on The Binary Computer, sees
0.565 as being a character string.  When you implicitly decide to use
"0.565" as a number *1*, Perl, and the underlying system, makes an effort
to convert this character string to the CPU's native floating
representation.  THIS IS NOT AN EXACT PROCESS *2*  *3*.   

Subsequently, when you try to print out the number, and you specify to
sprintf() that you want rounding to occur, it isn't clear what
sprintf() should do in this case -- round up or round down?  Either
choice would be reasonable.

There are many methods of doing rounding, and nearly all of these are
imcompatable.  If rounding is very important to your application, then
you really need to write your own rounding function -- the system
can't do it for you.  *4*


OBTW, your problem isn't specific to Perl.  Perl just uses the
underlying system to do all of the work for you.  C, C++, and yes,
even Python exhibit this behavior as well.

Regards,

--kevin

*1* You are implicitly using floating point, BTW.

*2* WORSE, you might be lulled into the belief that this is an exact
    process, since if you attempt to convert this floating point
    number to a string with a certain degree of precision, you'll seem
    to get your original number back.

*3* Interesting fact of the day:  Using binary, it is possible to
    exactly represent some numbers that cannot be exactly represented
    in base-10.

*4* I'll be you can find a Math:: library that does what you think is
    the right thing here.  Perhaps try Math::FixedPrecision .


-- 
"I'm on the bike and I go into a rage -- I shriek for about five
 seconds, I shake like mad, my eyes kind of bulge, and I'd never quit.
 That's heart.  That's soul.  That's guts"
    -- Lance Armstrong




More information about the gnhlug-discuss mailing list