problem with money datatype based calculations in python

Dave Angel davea at ieee.org
Sat May 2 10:09:55 EDT 2009


Krishnakant wrote:
> hello all,
> I am using postgresql as a database server for my db application.
>
> The database is related to accounts and point of sales and many
> calculations involve money datatype.
>
> The application logic is totally done in python.  Now the problem is
> that there is a situation where we calculate tax on % of the total
> amount on the invoice.  The  percentage is in terms of float but the
> eventual amount has to be in a money datatype.
>
> The product cost comes in money datatype from postgresql and the tax %
> comes in float.  So I would like to know if python supports some thing
> similar to money datatype so that I can cast my total amount (in money )
> divided by tax% (in float ) so money divided by float should be the
> result and that result should be in money datatype.
> For example a product x has the cost Rs. 100 which is stored in the
> tabel as money type.  and in the tax table for that product the VAT is
> 5% and this 5% is stored in float datatype.  So after using both these
> values the resulting total 105Rs. should be in money type and not float.
> I awaite some reply,
> Thanks in advice.
> happy hacking.
> Krishnakant.
>
>
>   
Tax rate isn't divided, it's multiplied.  But probably that's just a 
typo in your message.

Short answer is use your money class to convert the float into money.  
And then test, to see that's really what you wanted.  Be sure and check 
the edge cases, because float is a binary system, and you can get both 
quantization and rounding problems converting between them.

Is the money you're dealing with decimal-based?  So maybe money values 
are integers plus two more digits of fractional precision?

It's going to be tough for somebody with no access to that "money type" 
to guess what your problem is.  What operations does it currently 
support?  If it supports multiply, then just change the tax rate to be a 
money type.  Unless of course you might have a tax rate of 5.221%   Does 
your money class support accurate conversion to class decimal?  In that 
case, convert to decimal, multiply, then convert back.

Or if money is really a fixed-point class, with assumed two digits, 
multiply the cost by 100 and convert to int.  Multiply by the tax, and 
convert back.

You also need to specify the government rules for the multiply.  Is 
rounding permitted, or must all fractions of a penny (assumption there) 
be rounded up?

Or switch everything to "class decimal" in the standard python library,  
You still have most of the questions to answer, but at least you'd be 
asking on the right forum.





More information about the Python-list mailing list