[Tutor] How to correct decimal addition.
Dave Angel
davea at davea.name
Sat Jan 25 01:39:41 CET 2014
Leon S <imtherealleon at gmail.com> Wrote in message:
> _
(please post in plain text in this text mailing list. Html messes
up formatting and causes some newsreaders grief.)
......................
Leon said:
Here is what I'm trying to do, accept a price of gas, but I want
to add the .009 to the price, so that people do not have to type
the full amount. Â Example, 3.49 /gallon would return 3.499
/gallon.
This is what I have tried and the results of it.
def gas_price(price):
price == raw_input("What is the price of gas?") return price + .09
3.49
=> 3.4899999999999998
It reduces the number and then adds many decimal points after.
Thanks for any help, I am sure this is an easy one for someone
..............................
That stackoverflow link has lots of good information and some
disinformation.
First the code you show won't run, even after fixing the
formatting. Please use copy/paste. But making some assumptions,
I'm guessing you're adding two float objects and wondering why
the result is off when printed.
float is a binary floating point object and cannot represent
precisely decimal float values like three point forty nine. You
get quantization errors by definition, and must deal with them
somehow before the user sees them. You can fix that either by not
using binary (perhaps the decimal module? ) or by rounding when
you convert to string before printing.
Next time, post in text format, include all your code (no print or
equivalent in what you posted ), and tell us what version of
python you're using.
>
--
DaveA
More information about the Tutor
mailing list