Money data type

John Roth newsgroups at jhrothjr.com
Mon Sep 22 06:55:20 EDT 2003


"Terry Hancock" <hancock at anansispaceworks.com> wrote in message
news:q8Sdna1v7JgzKfOiXTWJkw at august.net...
> 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. ;-)

There's actually a rather simple conceptual difference. Scientific
and engineering computation deals with continuous quantities,
financial calculations deal with discrete quantities. Floats are an
adequate appromimation to continuous quantities (at least, if you
pay careful attention to precision and error bounds) while integers
are correct for discrete quantities. It's not a matter of "better"
or "worse." It's a matter of the correct tool for the job.

John Roth
>
> Cheers,
> Terry
>






More information about the Python-list mailing list