Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Re^4: perl subtraction

by dsheroh (Monsignor)
on Jan 10, 2010 at 11:25 UTC ( [id://816596]=note: print w/replies, xml ) Need Help??


in reply to Re^3: perl subtraction
in thread perl subtraction

Just multiplying by 100 doesn't make the errors go away. You still need to round off the result to produce an integer.

Consider:

If you have the value 1/3, or 0.333333333... (using a periodic decimal number rather than a periodic binary number for simplicity), of a dollar and you multiply it by 100, you get 33.333333... cents, which is still not equal to 33 cents. You have to round the 33.333333... off to just 33 before they'll be equal.

In this particular example, you could use int $val to convert the floating-point 33.333333... to the integer 33, but, in the general case, you'd probably want to use int ($val + 0.5) for simple rounding like I was taught in elementary school (always round 1/2 up), assuming you're only working with positive values. If you have to cope with negative numbers or if the accumulation of errors from always rounding 0.5 up would be an issue, then you should check CPAN for modules which implement a rounding technique appropriate to your needs.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others sharing their wisdom with the Monastery: (3)
As of 2024-04-25 09:27 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found