I have a list which consists of float values but they’re too detailed to proceed. I know we can shorten them by using the ("%.f" % variable)
operator, like:
JavaScript
x
4
1
result = [359.70000000000005]
2
result = "%.2f" % result
3
result = [359.70]
4
My question is how can I turn a list of values into their rounded equivalents without using an iterator. I’ve tried something, but it throws a TypeError
:
JavaScript
1
4
1
list = [0.30000000000000004, 0.5, 0.20000000000000001]
2
list = "%.2f" % list
3
TypeError: not all arguments converted during string formatting
4
How can I provide a clean list like:
JavaScript
1
2
1
list = [0.30, 0.5, 0.20]
2
Advertisement
Answer
"%.2f"
does not return a clean float. It returns a string representing this float with two decimals.
JavaScript
1
3
1
my_list = [0.30000000000000004, 0.5, 0.20000000000000001]
2
my_formatted_list = [ '%.2f' % elem for elem in my_list ]
3
returns:
JavaScript
1
2
1
['0.30', '0.50', '0.20']
2
Also, don’t call your variable list
. This is a reserved word for list creation. Use some other name, for example my_list
.
If you want to obtain [0.30, 0.5, 0.20]
(or at least the floats that are the closest possible), you can try this:
JavaScript
1
2
1
my_rounded_list = [ round(elem, 2) for elem in my_list ]
2
returns:
JavaScript
1
2
1
[0.29999999999999999, 0.5, 0.20000000000000001]
2