12

Is there anyway I could round-up numbers within a tuple to two decimal points, from this:

('string 1', 1234.55555, 5.66666, 'string2')

to this:

('string 1', 1234.56, 5.67, 'string2')

Many thanks in advance.

DGT
  • 2,604
  • 13
  • 41
  • 60
  • 2
    There is related thread on SO : http://stackoverflow.com/questions/455612/python-limiting-floats-to-two-decimal-points – pyfunc Oct 13 '10 at 22:33

3 Answers3

16

If your tuple has a fixed size of 4 and the position of the floats is always the same, you can do this:

>>> t = ('string 1', 1234.55555, 5.66666, 'string2')
>>> t2 = (t[0], round(t[1], 2), round(t[2], 2), t[3])
>>> t2
('string 1', 1234.56, 5.67, 'string2')

The general solution would be:

>>> t2 = tuple(map(lambda x: isinstance(x, float) and round(x, 2) or x, t))
>>> t2
('string 1', 1234.56, 5.67, 'string2')
tux21b
  • 90,183
  • 16
  • 117
  • 101
  • This is a duplicate. The link has been provided as comment. It would be better to just point to it and mark this question as duplicate. – pyfunc Oct 13 '10 at 22:36
  • 3
    The link wasn't there when I've written my answer, and the questions might be different. Maybe he has troubles to deal with the tuple and not with floating point arithmetic in general? – tux21b Oct 13 '10 at 22:41
  • 3
    @pyfunc I wouldn't say it's a duplicate. It's related but I think the "general solution" posted by @tux21b is what the OP may be trying to get at. At least that's how I understand it, how to round floats/doubles in a tuple that contains other values of other types. – Davy8 Oct 13 '10 at 22:43
  • 1
    @pyfunc: It's RELATED not DUPLICATE. The OP's problem may well be that `atuple[1] = round(atuple[1], 2)` fails whereas it works with a list. Novel thought: try asking the OP what his real problem is. – John Machin Oct 13 '10 at 22:44
3

List comprehension solution:

t = ('string 1', 1234.55555, 5.66666, 'string2')
solution = tuple([round(x,2) if isinstance(x, float) else x for x in t])
Andrey Gubarev
  • 771
  • 4
  • 6
1

To avoid issues with floating-point rounding errors, you can use decimal.Decimal objects:

"""
>>> rounded_tuple(('string 1', 1234.55555, 5.66666, 'string2'))
('string 1', Decimal('1234.56'), Decimal('5.67'), 'string2')
"""
from decimal import Decimal
def round_if_float(value):
    if isinstance(value, float):
        return Decimal(str(value)).quantize(Decimal('1.00'))
    else:
        return value

def rounded_tuple(tup):
    return tuple(round_if_float(value) for value in tup)

rounded_tuple uses a generator expression inside a call to tuple.

Community
  • 1
  • 1
intuited
  • 23,174
  • 7
  • 66
  • 88