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.
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.
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.
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.
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.
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')
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])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With