rounding-up numbers within a tuple

后端 未结 3 1261
囚心锁ツ
囚心锁ツ 2021-01-19 01:53

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

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

3条回答
  •  [愿得一人]
    2021-01-19 02:27

    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.

提交回复
热议问题