Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rounding-up numbers within a tuple

Tags:

python

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.

like image 428
DGT Avatar asked Oct 13 '10 22:10

DGT


People also ask

How do you round a number in Python tuple?

round () function in Python. Python round () function float point number from the decimal value to the closest multiple of 10. If two multiples are equally close, rounding is done toward the even choice.

Does Python round 0.5 up or down?

In Python, the round() function rounds up or down? The round() function can round the values up and down both depending on the situation. For <0.5, it rounds down, and for >0.5, it rounds up. For =0.5, the round() function rounds the number off to the nearest even number.

Is there a way to round numbers in Python?

Python has a built-in round() function that takes two numeric arguments, n and ndigits , and returns the number n rounded to ndigits . The ndigits argument defaults to zero, so leaving it out results in a number rounded to an integer.

Does .2f round Python?

We can also use % instead of format() function to get formatted output. It is similar to the format specifier in the print function of the C language. Just use the formatting with %. 2f which gives you round down to 2 decimal points.


2 Answers

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')
like image 166
tux21b Avatar answered Oct 17 '22 11:10

tux21b


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])
like image 3
Andrey Gubarev Avatar answered Oct 17 '22 13:10

Andrey Gubarev