Write float vaue to CSV, not true value

1,089 views
Skip to first unread message

Ann Carroll

unread,
Nov 26, 2014, 11:54:40 AM11/26/14
to psychop...@googlegroups.com
Using PsychoPy 1.77, in the builder, I am trying to take numbers from my conditions file and write them to a new csv file. For example, PsychoPy is reading numbers like .17, .25, .84 -- and I want the program to write them to the csv exactly like that (i.e. numbers rounded to two decimal places). Instead, when I use TextWrangler to look at the output, I am getting true values (i.e. .170000001, .2499999999996, .8400000000000002). 

How can I fix this? I know that float_format exists, but I haven't been able to get it to work. This has never been a problem for me before, but started to be an issue for some reason today.

Thanks!

Mario Reutter

unread,
Nov 27, 2014, 5:57:26 AM11/27/14
to psychop...@googlegroups.com
Hi,

I'm not familiar with the builder but a code snippet that calls python's round()-function should help: round(number, 2) #rounds the number to two digits after the decimal point
Maybe you could even spare the code snippet and call the round function within the command that creates the csv output (I'm using Python's csv.writer.writerow()-function and don't know what the builder provides).

Another idea would be to read the numbers as Strings instead of float values (in coder: str()-function). If this works for the csv output you might have to adjust some comparisons like
if condition == .17
to
if condition == ".17"
i.e. compare to a String instead of to a number.

Hope this helps you despite the emphasis on a coder solution ;)
Mario

Ann Carroll

unread,
Dec 1, 2014, 5:21:22 PM12/1/14
to psychop...@googlegroups.com
Thanks, Mario! Before your response I managed to figure out how to use the float_format component of 'to_csv.' See http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.to_csv.html

Working code:
dataFrame.to_csv(file, float_format = '%.2f')
Reply all
Reply to author
Forward
0 new messages