Money data type

Terry Hancock hancock at anansispaceworks.com
Mon Sep 22 04:39:15 EDT 2003


Batista, Facundo wrote:
> Are you trying to tell me that if I work always with float, and in the
> final step (reaching the user's eyes or check in the printer) I
> "represent" it with str (for example) or with "%.5f", I get no rounding
> errors?
> 
> If you are, I will believe you! (even "feeling" other way, but can not
> prove it).

Nope, you will indeed get small errors if you do this -- at least you will
if you work with very large amounts of money in the calculations.  The
only way to "not drop pennies" is to represent them with integers.

Specifically, Python long integers have arbitrary size (they are limited
by memory, not any fixed upper limit as are normal ints in python and
integer types in languages like C).

I'm pretty sure that the fixed point library that was mentioned does
exactly this -- it represents the numbers in the same way as the Python
long, but with the decimal point moved to a certain place.

People who are used to scientific and engineering computations don't
worry about this -- there are well-defined ways to avoid trouble from
rounding errors in those fields, and the need for numbers that can
represent arbitrarily large and small values in a compact way far outweighs
the precision advantage of integer or fixed-point representations.

I say this after having had this point proved to me, since I tended to
be from the "why not use floats" school, myself.  Whether in some
moral sense we *should* be concerned about pennies in a number like
the US national debt, is a philosophical issue I don't think we can
do justice to here. ;-)

Cheers,
Terry

-- 
Terry Hancock
Anansi Spaceworks http://www.AnansiSpaceworks.com/





More information about the Python-list mailing list