another fp problem

Jp Calderone exarkun at intarweb.us
Mon Oct 6 10:15:22 EDT 2003


On Mon, Oct 06, 2003 at 10:27:02PM +1000, Michael Hall wrote:
> Hi All:
> 
> I'm a relative newbie to Python, apart from some CGI and shell scripting type
> stuff. Anyway, I'm having some problems doing maths in Python 2.2.2 on RH9.
> 
> I'm wondering what is the best way or numerical data type to do simple monetary
> calculations in Python? I only need to work with decimal numbers to two decimal
> points. Are floating point numbers the only option? They're giving me hell!
> 
> If floating point numbers are the only option, how can I round off a number to
> two decimal points? Converting to an integer is not working ... the cents disappear.
> 
> Leaving valuse as floating point is also not working ... I end up with figures
> like $35.33000000018.
> 
> BTW, I'm putting values in and out of a MySQL database (DECIMAL data type) using
> MySQLdb. The values giving me the most grief have been pulled out of the
> database, where they look just fine.
> 
> Any advice graetly appreciated.

  Multiply everything by a hundred, use integers which correspond to numbers
of cents.

  If this simplistic approach doesn't cover all your needs, look into using
a fixed point type (there are none in the stdlib, but modules which
implement them are available -- check google).

  Jp





More information about the Python-list mailing list