float safety clarification

Michal Wallace sabren at manifestation.com
Mon Jun 26 09:18:20 EDT 2000


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
------------------------------------------------------------------------
www.manifestation.com  www.sabren.com  www.linkwatcher.com  www.zike.net
------------------------------------------------------------------------






More information about the Python-list mailing list