On 01/25/2014 09:46 AM, spir wrote:
On 01/24/2014 06:57 PM, Leon S wrote:
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.

This is instead easy for noone ;-)

The core issue is that for, say, "fractional numbers" (numbers with a fractional
part, but unlike real numbers with definite precision) python like most
programming languages uses in standard a binary representation internally. While
we normally use decimal notation, both in input (reading) and output (writing).
And there is no way to represent decimal fractions in binary, except in the very
case where they are a multiple of an exact (negative) power of 2 (for instance
1/2, 3/4, 123/128... are ok).

The only right solution is to use decimals internally, and python provides such
a numeric type, Decimal:
http://docs.python.org/3/library/decimal.html

I did not read correctly. If you're dealing with financial as it seems, the right way is to use integers instead. Since you are adding tenth's of pence, this is what your unit means. Then your sum is:
        3490 + 9
:-)

Note: AFAIK most financial software use integers for this reason and to avoid (or control) rounding errors.

At input and/or output, you may still have to convert to Decimal to get "decimally correct" value or expression.

        numeral = input("...")
        value = Decimal(numeral)
        ...
        output = Decimal(result) / Decimal("1000")
        print(output)

(not sure, not tried)

d
_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

Reply via email to