I am using Mathematica to post-process data and end up with machine precision artifacts that produce unwanted digits when exporting as CSV. See this example:
x=1+10^-9 -1.; ExportString[x,"CSV"] 1.000000082740371e-9
So, I figured I use NumberForm[]
to reduce the precision of x. But apparently CSV-Export does not know how to handle NumberForm (nor EngineeringForm): ExportString[NumberForm[x, {4,3}], "CSV"]
produces multiline output (FullForm)
" -9\n1.000 \[CapitalATilde]\.97 10\n"
or, with CharacterEncoding -> "ASCII"
,
" -9\n1.000 x 10\n"
Not something Excel would read. I expect 1.000e-9
.
As this question has been closed I cannot answer my own question, but I can still edit it:
One solution is hand-crafting the NumberFormat like this:
ExportString[ NumberForm[x, {4, 3}, NumberFormat -> (If[#3 == "", #1, Row[{#1, "e", #3}]] &)], "CSV"]
If you only want to get rid of the unwanted digits, but do not care for a fixed number of digits you can also just use
ExportString[SetPrecision[x, 5], "CSV"]
ExportString[NumberForm[1.2 10^-9, 4], "CSV", CharacterEncoding -> "ASCII"]
works. Also note that there are quite a few questions about exporting tables/numbers to CSV :)$\endgroup$