float safety clarification
John W. Baxter
jwbnews at scandaroon.com
Mon Jun 26 11:35:39 EDT 2000
More information about the Python-list mailing list
Mon Jun 26 11:35:39 EDT 2000
- Previous message (by thread): SMTP with Python 1.6
- Next message (by thread): float safety clarification
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
In article <Pine.BSF.4.10.10006260856360.16661-100000 at chi.pair.com>, Michal Wallace <sabren at manifestation.com> wrote: > Hey all, > > I'm building a shopping cart, so I want to be able to store and work > with prices. I've always been told that you shouldn't use floats for > money. From past discussions here, I even understand why floats can be > inaccurate... But in actually trying it out, I can't seem to produce > any real-world situations relevant to my cart where using floats would > screw me up... I guess I'm asking for a sanity check here. > > Are floats safe to use for money values if you're only going to be > adding and subtracting them, or multiplying them? > > I tried this: > > >>> for x in range(100): > ... print "%.2f" % (float(x)/100), > > And it looks right. I haven't gotten any funny results with just > adding or subtracting.. > > Here are the operations I need to perform: > > - assign a price > - multiply price by (whole number) quantity > - add a bunch of prices together > - calculate a sales tax > - possibly some day give a percent discount > > I thought sales tax might be a problem, but I haven't been able to > come up with a problem where a percent sales tax represented as a > float causes any float problems, either. > > Basically, I can't find a reason not to use floats. > Am I asking for trouble? > > Cheers, > > - Michal You'll probably be OK as long as you don't compare (with 0.00, or with any other specific value). Are you doing something like offering free shipping on orders of $100 or more? Comparison against 100 or 100.00 could produce a wrong answer if the sum of the items is slightly less than 100. Same for free shipping "over $100"...you might have a total "equal" to 100 for which sum > 100.00 is true (less bad: you aren't failing to give something you should have, landing in FTC hell). I wouldn't do it...I see no reason to work with decimal money with a method which expresses only 4% of the possible 100 different cents values exactly (.00, .25, .50, .75). --John -- John W. Baxter Port Ludlow, WA USA jwbnews at scandaroon.com
- Previous message (by thread): SMTP with Python 1.6
- Next message (by thread): float safety clarification
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
More information about the Python-list mailing list