Numeric data question

Chris Barker Chris.Barker at noaa.gov
Wed Jul 24 15:02:07 EDT 2002


terry wrote:
> I'm guessing now (from lack of real experience) that being a
> 'typeless' language

Python is "dynamically, but strongly typed" which is an important distinction.

> that I would be forced into contriving a
> method for handling money such that I could never code something
> straightforwardly like:
> TotalCost = Quantity * UnitCost
>  (where Quantity is integer and the others money).

You might have to contrive something, but it would allow you to code:

> something straightforwardly like:
> TotalCost = Quantity * UnitCost
>  (where Quantity is integer and the others money).

To keep the buzzwards rolling, Python is an Object Oriented language
that supports Operator Overloading. What you can do is create a class,
"money" that defines the arithmetic operators the way you want them to
be used. You can do this is such a way that it interacts appropriately
with Python numeric types, and uses all the standard operators.

> Am I loonie, or is Python just not inherently suitable for
> accounting applications for this reason?

Do any programming languages have a built in "money" type? How is this
problem solved in them? If this really is a problem that can't be
handled by using floating point and rounding appropriately where
required, I imagine someone out there has written a money class already.
If not you will be doing a service to the community if you do it.

no comment on whether you are loonie or not.

-Chris

Here is a trivial example to get you started. You would obviuosly have
to be very carefull about rounidng and all that to do it right:

#!/usr/bin/env python2

import string
 
class money:
    def __init__(self,amount, flag = "dollars"):
        if flag == "dollars":
            self.micropennies = long(round(amount,2)*100000000)
        elif flag == "pennies":
            self.micropennies = long(round(amount)*1000000)
        elif flag == "micropennies":
            self.micropennies = long(amount)

    def __str__(self):
        return "$%i."%(self.micropennies /100000000)+
                       string.zfill(int(((self.micropennies /
                                          1000000) % 100)),2)

    def __mul__(self,other):
        return money(self.micropennies * other,"micropennies")

    def __rmul__(self,other):
        return money(self.micropennies * other,"micropennies")
        


UnitCost = money(23.45)
print "UnitCost is:  ", UnitCost
Quantity = 5
TotalCost = Quantity * UnitCost
print "TotalCost is: ",TotalCost


-- 
Christopher Barker, Ph.D.
Oceanographer
                                    		
NOAA/OR&R/HAZMAT         (206) 526-6959   voice
7600 Sand Point Way NE   (206) 526-6329   fax
Seattle, WA  98115       (206) 526-6317   main reception

Chris.Barker at noaa.gov



More information about the Python-list mailing list