Why not FP for Money?

Carlos Ribeiro carribeiro at gmail.com
Thu Sep 23 08:32:34 EDT 2004


On 23 Sep 2004 11:56:40 GMT, Duncan Booth <duncan.booth at invalid.invalid> wrote:
> Can you give a use-case where you would actually write $1.00 + 0.99212
> rather than, say, 'balance + interest'?

For systems development, you're probably right. But for
quick-and-dirty scripting or even interactive usage, a direct notation
is cleaner, more readable, and les obstrusive than to have to specify
it as in:

Money("1.00")
 
> For that matter can you give a use case where you actually need to write
> fixed point decimal literals in your code rather than taking them out of a
> configuration file?

Well, actually I don't see any reason why I should be precluded from
writing fixed point literals in my code. Why should I need a
configuration file, or a database, for everything that I do with fixed
point numbers? That's similar to saying that I don't need to be able
to write Unicode literals, because I can always read them from a file
(and you know how much trouble Unicode support is right now --
encoding stuff, etc).

Besides that, that's a problem with convenience. 2.4 Decimal type
can't be constructed from a float -- one has to use a string. I think
this does introduce unnecessary clutter in code. That's a quote from
from : What's new on Python 2.4":

http://www.python.org/dev/doc/devel/whatsnew/node8.html
"""
Converting from floating-point numbers poses a bit of a problem:
should the FP number representing 1.1 turn into the decimal number for
exactly 1.1, or for 1.1 plus whatever inaccuracies are introduced? The
decision was to leave such a conversion out of the API. Instead, you
should convert the floating-point number into a string using the
desired precision and pass the string to the Decimal constructor:
"""

PEP327 also does mention it:

http://www.python.org/peps/pep-0327.html#explicit-construction:
"""
So, the accepted solution through c.l.p is that you can not call
Decimal with a float.
"""

So, in order to construct a Decimal, I need to write something like:

>>> a = decimal.Decimal('35.72')
>>> b = decimal.Decimal('1.73')
>>> a+b
Decimal("37.45")

But I could write it this way (just an example; my proposed notation
is for fixed point, not floating point decimal):

>>> a = $35.72
>>> b = $1.73
>>> a+b
$37.45

And it would work. That's nice, clean, and reads quite obviously --
even if using a symbol as part of the syntax.

--
Carlos Ribeiro
Consultoria em Projetos
blog: http://rascunhosrotos.blogspot.com
blog: http://pythonnotes.blogspot.com
mail: carribeiro at gmail.com
mail: carribeiro at yahoo.com



More information about the Python-list mailing list