another fp problem

Joerg Sonnenberger joerg at britannica.bec.de
Mon Oct 6 19:40:24 CEST 2003


On Mon, 06 Oct 2003 23:27:02 +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!

There is no monetary type yet, i.e. fixed point full precision for adds.

> 
> 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.

You are asking the wrong question. The problem is 35.33 is a finite binary
fraction like 35.25 is. There a few thing you can do in python. Use normal
integer arithmetic with a power of ten as exponent i.e. the normal
scintific notation with an integer mantisse (3533 * 10**-2). Build a class
around it to implement the involved operations and provide a __float__
function for the conversion by MySQLdb.

> 
> 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.

Perhaps you can get them as strings? Split the string in to get the number
of digits after the decimal point and set up a class like that mentioned
above.

Joerg

> 
> Any advice graetly appreciated.
> 
> Mick
> 
> ------------------------------------------
> Ninti Systems: Linux Solutions and Support
> Michael Hall
> Mobile: 0429 095 392
> Ph/Fax: 08 8953 1442       
> Email:  office at ninti dot com
> Web:    http://ninti.com
> ------------------------------------------

------------ And now a word from our sponsor ------------------
Want to have instant messaging, and chat rooms, and discussion
groups for your local users or business, you need dbabble!
--  See http://netwinsite.com/sponsor/sponsor_dbabble.htm  ----




More information about the Python-list mailing list