Why not FP for Money?

Jeff Shannon jeff at ccvcorp.com
Fri Sep 24 21:47:46 EDT 2004


Carlos Ribeiro wrote:

>A last note: unless dictated by context otherwise, I think that adding
>two fixed point numbers should round/truncate to the smallest number
>of decimal places, as in:
>
>12.34d + 10.001d --> 32.34
>  
>

Personally,  I think that it makes the most sense (i.e., will result in 
the fewest surprises) if the greatest possible number of places is 
preserved.  If you truncate decimal places, then you might get this:

    x = 1.1d
    for _ in range(5):
        x += 0.02d
    print x              ----> 1.1d

Each addition of 0.02 to 1.1 yields 1.12, which is truncated back to 
1.1, which leaves us in the same place that integer division did.  I 
think it's pretty clear that this *should* produce 1.2.  In order to do 
that, you need to preserve the largest number of decimal places.

But it's even more delicate than that -- does 0.3d / 2 result in 0.1d, 
0.2d, or 0.15d ?  Anything other than the last will surprise people, but 
allowing the number of decimal places to grow implicitly is surprising 
in other circumstances.

I'd suspect that all of this would need to be configurable by context, 
but I'd suggest that the default should be to use as many decimal places 
as are necessary to preserve precision (i.e., 0.3d / 2 --> 0.15d), up to 
some (reasonably large) maximum number of places.  (That maximum would 
be configurable, too.)

Jeff Shannon
Technician/Programmer
Credit International






More information about the Python-list mailing list