[Tutor] How to correct decimal addition.

spir denis.spir at gmail.com
Sat Jan 25 09:46:14 CET 2014


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

d


More information about the Tutor mailing list