String/Decimal issues

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sun Nov 11 00:02:19 CET 2007


On Sat, 10 Nov 2007 09:02:01 -0800, Mike Howarth wrote:

> Hi
> 
> Seem to be having a bit of brainfreeze this evening.
> 
> Basically I'm reducing an array of prices like so:
>>> subtotal = reduce(operator.add, itemprices)
> 
> This gives me a string of '86.00.00' which I am trying to use with
> decimal objects. Python 2.4 is not particularly happy with this.

Let me guess... your test data is:

itemprices = ['86.0', '0.00']

What happens if you use test data like this?

itemprices = ['86.0', '0.00', '1.99', '12.03']



The first problem that you have is that your prices are strings. Is that 
deliberate? This is not necessarily a fault.

Your second problem is that the + operator concatenates strings, not adds 
them. "1.0" + "2.0" = "1.02.0", not "3.0". This, on the other hand, is 
absolutely a fault. Your code is producing invalid data.


> Additionally I can't simply convert the string to a decimal as it would
> be invalid given it has multiple decimal points.

Yes. Rather than trying to fix the invalid data after it is produced, you 
should fix your code so it doesn't produce the wrong answer in the first 
place.


> Being relatively new to python, I'm not sure how I could round the
> string or similar. Anyone got any ideas?


This is NOT the answer you NEED, but this is the answer you ask for. To 
cut out the extra decimal places, use this:

>>> subtotal = '86.00.00'
>>> subtotal[:-3]
'86.00'

Now that I've told you how to do it, let me re-iterate that you shouldn't 
do it. Your problem isn't that your result has an extra ".00" at the end 
of the result. Your problem is that your result is WRONG. Fix the result 
in the first place.

I'd be looking at something like this:


# start with a list of strings
itemprices = ['86.0', '0.00', '1.99', '12.03']
# convert them into decimal objects
itemprices = map(decimal.Decimal, itemprices)
# and add them
subtotal = sum(itemprices)



-- 
Steven.



More information about the Python-list mailing list