If you can isolate the number you want to round, you can format it to two decimal places and store it as a string like this:
"%.2f" % myNum
Question
I have data which looks like
[('A',5.3748),('B',8.324203),('C',3.492)]
I'm saving it to a csv with the following lines:
with open('output.csv','wb') as fp:
a = csv.writer(fp,delimiter = ",")
a.writerows(data)
Works like a charm except that I would like to display my values with only two decimal digits. Earlier in my code I zip two lists to get the data. So I could make the change before if need be.
Thanks!
La solution 2
If you can isolate the number you want to round, you can format it to two decimal places and store it as a string like this:
"%.2f" % myNum
Autres conseils
You can use the string formatting syntax:
with open('output.csv','wb') as fp:
a = csv.writer(fp,delimiter = ",")
a.writerows(map(lambda t: (t[0], "%.2f" % t[1]), data))
The trick is here:
>> "%.2f" % a_number
will print the number with two decimal digits, while
map(lambda t: (t[0], "%.2f" % t[1]), data)
will apply this transformation to every tuples in the list data
. (see http://docs.python.org/2/library/functions.html#map)
from itertools import imap
with open('output.csv','wb') as fp:
a = csv.writer(fp,delimiter = ",")
a.writerows(imap(lambda x: (x[0], round(x[1], 2)), data))
Try formatting your decimals using str.format()
:
temp = [('A',5.3748),('B',8.324203),('C',3.492)]
newlist = []
for a, b in temp:
newlist.append((a, "{0:.2f}".format(b)))
As a list comprehension, you get:
data = [('A',5.3748),('B',8.324203),('C',3.492)]
data = [(a, "{0:.2f}".format(b)) for a, b in temp]
As @JonClements noted, you can replace "{0:.2f}".format(b)
with format(b, '.2f')
. In this case, that's probably the more readable approach.
You can also use python's round() method.
round(5.3748, 2)
The advantage of using this with a csv writer is that it maintains it's number type instead of being converted to a string. This affects options like quoting non-numericals in the csv file.
If you don't need to worry about such formatting options I personally prefer formatting it to a string, since it aligns the correct number of decimal places even if they are zero. I.e. 5.3748 to "5.3700" instead of 5.37
You can format the list elements as follow
linux:~ # python
>>> l=[('A',5.3748),('B',8.324203),('C',3.492)]
>>> l=[ (x[0], "%.2f" % x[1]) for x in l]
>>> l
[('A', '5.37'), ('B', '8.32'), ('C', '3.49')]