Money data type

Andy Jewell andy at wild-flower.co.uk
Wed Sep 17 15:40:06 EDT 2003


On Wednesday 17 Sep 2003 7:28 pm, Batista, Facundo wrote:
> Can't find it.
>
> I mean something like:
> >> m1 = Money(decimal=2)
> >> m2 = Money(decimal=2)
> >> m1.value = 3.20
> >> m2.value = 2.15
> >> print m1 + m2
>
> 5.35
>
> 5.35! Not 5.3500000000000001 neither 5.34999999999999999999.
>
> I think this is not a rare thing, but I can't find it in the standar
> library neither the package index.
>
> Thanks!
>
> .	Facundo

Facundo,

When you just print a raw float, it will be printed to its most accurate 
decimal representation.  If you need /aritrary precision/ you are probably 
best off using long-integers, multiplying your result, say by 100 (e.g. for 
two decimal place precision) and then dividing down again when you need to 
print.

Actually, though, I think what you need is:

-----8<-----
>>> m1=3.2
>>> m2=2.15
>>> print "%4.2f" % (m1+m2)
5.35
>>> print m1+m2
5.35
>>> # oops... lets try someting a little more difficult
>>> m3=100.0/3
>>> m3
33.333333333333336
>>> print "%4.2f" % m3
33.33
>>> m3
33.333333333333336
>>> print "%4.2f" % (m3+m2)
35.48
>>> m3+m2
35.483333333333334
>>> 
-----8<-----

hth,
-andyj





More information about the Python-list mailing list