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.

2 Answers 2

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]

Sign up to request clarification or add additional context in comments.

Comments

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.