0

How do you format a float to 2 decimal points with mixed data type? I'm fetching a table and writing rows to csv file. My data is (string, string, float, float, float...)

    sql = 'select * from testTable'
    c.execute(sql)

    columnNames = list(map(lambda x: x[0], c.description))
    result = c.fetchall()

    with open(outputCSVPath, 'wb') as f:
        writer = csv.writer(f)
        writer.writerow(columnNames)
        writer.writerows(result)

With the above code, I get floats with 6 decimal places. I need to format it to 2 decimal places but because of the first 2 of the list being string, it gives me an type error.

Thank you.

monty_bean
  • 494
  • 5
  • 25

2 Answers2

2

You need to change the 'result' list using list comprehension and ternary if-else in Python.

result = [x if type(x) is str else format(x,'.2f') for x in result]

Sachin
  • 3,576
  • 1
  • 15
  • 24
1

You can iterate the result in order to parse only the floats values, and then you can use writer.writerows(row) to write row by row. Take a look here to know the different ways to iterate your results.

On the other hand, you can format floats to two decimals points using the round() function from python.

An example:

>>> # Each of your rows should be something like: 
>>> list = ["string1", "string3", 1.435654, 4.43256]

>>> #Round the floats
>>> parsed_list = [round(x, 2) if i > 1 else x for i, x in enumerate(list)]

>>> print parsed_list
['string1', 'string2', 1.44, 4.43]
Community
  • 1
  • 1
edgarzamora
  • 1,472
  • 1
  • 9
  • 17