On Wed, May 30, 2001 at 09:44:29AM -0400, Ronald J Kimball wrote:
> On Tue, May 29, 2001 at 06:51:32PM +0100, Michael G Schwern wrote:
> > The perlfaq4 answer about floating point error should point out the
> > technique of working in integers and then converting to decimal at the
> > end.
> >
> > --- pod/perlfaq4.pod 2001/05/29 17:46:32
> > +++ pod/perlfaq4.pod 2001/05/29 17:48:38
> > @@ -39,6 +39,11 @@
> > (part of the standard Perl distribution), but mathematical operations
> > are consequently slower.
> >
> > +If precision is important, such as when dealing with money, its good
> > +to work with integers and then divide at the last possible moment.
> > +For example, work in pennies (1995) instead of dollars and cents
> > +(19.95) and divide by 100 at the end.
> > +
>
> s/its/it's/;
Thanks, applied.
I also added one more trick:
Change 10319 by jhi@alpha on 2001/05/30 13:06:09
Subject: Re: [PATCH pod/perlfaq4.pod] Example of working in integers to avoid
floating point errors
From: Ronald J Kimball <[EMAIL PROTECTED]>
Date: Wed, 30 May 2001 09:44:29 -0400
Message-ID: <[EMAIL PROTECTED]>
Detypo; plus add one more trick.
Affected files ...
... //depot/perl/pod/perlfaq4.pod#34 edit
Differences ...
==== //depot/perl/pod/perlfaq4.pod#34 (text) ====
Index: perl/pod/perlfaq4.pod
--- perl/pod/perlfaq4.pod.~1~ Wed May 30 17:06:16 2001
+++ perl/pod/perlfaq4.pod Wed May 30 17:06:16 2001
@@ -39,10 +39,20 @@
(part of the standard Perl distribution), but mathematical operations
are consequently slower.
-If precision is important, such as when dealing with money, its good
+If precision is important, such as when dealing with money, it's good
to work with integers and then divide at the last possible moment.
For example, work in pennies (1995) instead of dollars and cents
-(19.95) and divide by 100 at the end.
+(19.95) and divide by 100 at the end. In fact, if you are dividing by
+100, you don't even need to really divide-- just split of the
+fractional parts and insert the '.' (or whichever is your decimal
+separator) in between, e.g.
+
+ sub d100 {
+ $_[0] =~ /(.*?)(.(?:.)?)$/;
+ sprintf("%d.%02d", $1||0, $2);
+ }
+
+and then display all your numbers like this: C<d100($number)>
To get rid of the superfluous digits, just use a format (eg,
C<printf("%.2f", 19.95)>) to get the required precision.
End of Patch.
--
$jhi++; # http://www.iki.fi/jhi/
# There is this special biologist word we use for 'stable'.
# It is 'dead'. -- Jack Cohen