String/Decimal issues

Ben Finney bignose+hates-spam at benfinney.id.au
Sat Nov 10 16:47:23 EST 2007


Mike Howarth <hey at mikehowarth.co.uk> writes:

> Basically I'm reducing an array of prices like so:
> >> subtotal = reduce(operator.add, itemprices)
> 
> This gives me a string of '86.00.00'

You haven't shown what the input is; what is the value of 'itemprices'
before this line?

When I use floating-point numbers, I get this::

    >>> import operator
    >>> itemprices = [24.68, 12.34, 36.90]
    >>> itemprices
    [24.68, 12.34, 36.899999999999999]
    >>> subtotal = reduce(operator.add, itemprices)
    >>> subtotal
    73.919999999999987

When I use the Decimal type, I get this::

    >>> import operator
    >>> from decimal import Decimal
    >>> itemprices = [Decimal("24.68"), Decimal("12.34"), Decimal("36.93")]
    [Decimal("24.68"), Decimal("12.34"), Decimal("36.93")]
    >>> subtotal = reduce(operator.add, itemprices)
    >>> subtotal
    Decimal("73.95")

So I suspect your 'itemprices' sequence is composed of values of some
other type. Please show your equivalent of the above sessions so we
can see what's happening.

-- 
 \     "Don't be afraid of missing opportunities. Behind every failure |
  `\      is an opportunity somebody wishes they had missed."  -- Jane |
_o__)                                          Wagner, via Lily Tomlin |
Ben Finney



More information about the Python-list mailing list