diff options
author | Ronald J. Kimball <rjk@linguist.dartmouth.edu> | 2001-05-30 05:44:29 -0400 |
---|---|---|
committer | Jarkko Hietaniemi <jhi@iki.fi> | 2001-05-30 13:06:09 +0000 |
commit | 80ba158a8814f0a25ec880b4a3dfdce264efaa09 (patch) | |
tree | 06ce4c9633dd1ffcd4209c64bde710495e1728f7 /pod/perlfaq4.pod | |
parent | 5a02ccb1df652f2b0dd47663c285921ec8e27bd2 (diff) | |
download | perl-80ba158a8814f0a25ec880b4a3dfdce264efaa09.tar.gz |
Re: [PATCH pod/perlfaq4.pod] Example of working in integers to avoid floating point errors
Message-ID: <20010530094429.B133085@linguist.thayer.dartmouth.edu>
Detypo; plus add one more trick.
p4raw-id: //depot/perl@10319
Diffstat (limited to 'pod/perlfaq4.pod')
-rw-r--r-- | pod/perlfaq4.pod | 14 |
1 files changed, 12 insertions, 2 deletions
diff --git a/pod/perlfaq4.pod b/pod/perlfaq4.pod index 87fd66a777..4acd3d93a1 100644 --- a/pod/perlfaq4.pod +++ b/pod/perlfaq4.pod @@ -39,10 +39,20 @@ arbitrary-precision decimal numbers with the Math::BigFloat module (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. |