How to get only up to 2 float precision values of elements in a list without changing the Float type of the elements.
l = [[u'NY Disability Contribution', 2.6, 2.6, 2.6, 1.3, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 9.1],[u'Income Tax',387.32,387.32,387.32,193.66,0.0,0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0, 1355.62]]
Output should be like
result = [[u'NY Disability Contribution', 2.60, 2.60, 2.60, 1.30, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 9.10],[u'Income Tax',387.32,387.32,387.32,193.66,0.00,0.00, 0.00, 0.00,
0.00, 0.00, 0.00, 0.00, 1355.62]]
Eg: for 2.6 ---> 2.60
I've tried like this
result = [[i[0]] + [float(format(j,".2f")) for j in i[1:]] for i in y]
but those are coming as string values
my output
[[u'Contribution', '2.60', '2.60', '2.60', '1.30', '0.00', '0.00',
0.00', '0.00', '0.00', '0.00', '0.00', '0.00', '9.10'],
[u'Tax','387.32','387.32','387.32','193.66','0.00','0.00',
'0.00','0.00', '0.00', '0.00', '0.00', '0.00', '1355.62']]
Thanks in advance
If you absolutely want to display print(my_list)
with a 2 float precision, you cannot unless:
float
(or list
) and change the __repr__
method print(my_list)
and use a custom function to display your result Using the answer provided in Easy pretty printing of floats in python? , here is a possibility:
class prettyfloat(float):
def __repr__(self):
return "%0.2f" % self
result = [[i[0]] + [prettyfloat(j) for j in i[1:]] for i in y]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.