in reply to Re: perl subtraction
in thread perl subtraction

Hi,

I have written a script in which I enter the invoice amount, the tax amount, and the invoice total. Then I make the script check that the invoice amount + the tax amount equal the invoice total. It works well most of the time, but yesterday one invoice had these amounts (invoice amount = 17554.61, tax = 2194.33, and total = 19748.94) and the script informed me that the two figures were not equal. As you have explained, it does so because the internal base 2 representations of the two numbers are not the same. Is there any way of getting around this hurdle? How can perl be made to see that the two figures are the same in the decimal format?

Replies are listed 'Best First'.
Re^3: perl subtraction
by AnomalousMonk (Archbishop) on Jan 10, 2010 at 05:26 UTC

    One general approach is to maintain and operate on amounts internally as fixed-point integer quantities; e.g., as the number of cents, or possibly mills (tenths of a cent). While the numeric representation used (at least by Perl) is still double-precision floating point, the goal is to never produce a non-zero fractional result. Addition, subtraction and multiplication on integers always yield integer results. Operations that can produce fractional results (e.g., division) must sooner or later (and sooner is usually better) be reconciled into the fixed point representation that has been selected.

    Or maybe check out something like integer or Math::FixedPrecision.