Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

Re: perl subtraction

by syphilis (Archbishop)
on Jan 10, 2010 at 03:53 UTC ( [id://816569]=note: print w/replies, xml ) Need Help??


in reply to perl subtraction

It's because the internal base 2 representation of the result of adding 17554.61 and 2194.33 is not exactly the same as the internal base 2 representation of 19748.94.

Cheers,
Rob

Replies are listed 'Best First'.
Re^2: perl subtraction
by jagdish.eashwar (Novice) on Jan 10, 2010 at 04:46 UTC
    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?

      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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://816569]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others taking refuge in the Monastery: (7)
As of 2024-04-23 07:37 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found