http://www.perlmonks.org?node_id=115374

in reply to Rounding errors problem

Floating point arithmetic is inherently imprecise. Since you record as pennies, Math::BigInt might be a better choice than Math::BigFloat. Currency exchange rates are, in themselves, a bit fuzzy, so I suggest getting your spec clarified as to how rounding is done, what quotation is used, when the quote is changed, etc. There is an accountant somewhere in this job. There's where to get the real needs.

Update: If Math::BigInt is overkill, what do you need with Math::BigFloat? To round an ordinary perl number, a float, to an integer (\$n+.5)|0 or else sprintf "%.0f",\$n. Again, talk to the accountant.

After Compline,
Zaxo

Replies are listed 'Best First'.
Re: Re: Rounding errors problem
by perlcgi (Hermit) on Sep 28, 2001 at 16:06 UTC
Thanks for the input Zaxo.
The exchange rates are fixed and are offical Euro exchange rates. The invoice total, before conversion, equals the sum of the line items. After conversion they differ by a penny or so. I need to be sufficiently precise so that they are equal after conversion. The sums are not large, and would not require Math::BigInt.
Thanks again.
Perlcgi
The exchange rates are fixed and are offical Euro exchange rates. The invoice total, before conversion, equals the sum of the line items. After conversion they differ by a penny or so. I need to be sufficiently precise so that they are equal after conversion.
Maybe you don't get that this is not always possible. For example, consider a series of transactions of 103, 103, and 104 units. Those added together make 310 units. Now convert those into a currency that is 1/10 the size. We round 10.3 to 10 (twice) and 10.4 to 10 (once). The "total" should be 31, but it's really only 30. This is the way this works. You cannot always balance to the penny when you map values from one currency to another and it's considered fair accounting practice to simply note that and move on.

A parallel example: my brother noted that at a particular Washington State sales tax rate, it was cheaper by a penny to buy two single Big Gulps rung up separately than it was to buy them as a combined transaction. So whenever he had to buy two, he'd always buy one, pay, then buy the second one.

This is the real world, and it's accepted practice. Don't attempt the impossible. {grin}

You cannot always balance to the penny when you map values from one currency to another and it's considered fair accounting practice to simply note that and move on.

But note that noting that usually implies that the lost round-off amount is accounted for in a special "accumulate round-offs" account in the general ledger. I know we have such a beast at work. Otherwise (I hypothesise) you open yourself up to salami attacks.

--
##### g r i n d e r
D'oh! Its impossible! Perlcgi has an epiphany. That's the key insight! Thank you very much Randal. {grins back in humble appreciation}