Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exporting double value to CSV

I am trying to export double values to a CSV file as follows

double[] arr = new double[] { 0.0000074, 0.00000123, 0.0000001254 };
using (StreamWriter writer = new StreamWriter(@"D:\Test.csv"))
{
    foreach (double item in arr)
    {
        writer.WriteLine(item);
    }
};

The output when CSV is opened in Excel/Notepad is the same and is as follows

7.40E-06
1.23E-06
1.25E-07

Expecting the output to be same as the input in the CSV file. Looking forward to any kind of input/suggestions. Thanks.

like image 740
Subru Avatar asked May 30 '26 19:05

Subru


2 Answers

You could specify the format of the double string by putting floating-point format like "F9":

double[] arr = new double[] { 0.0000074, 0.00000123, 0.0000001254 };
using (StreamWriter writer = new StreamWriter(@"D:\Test.csv"))
{
    foreach (double item in arr)
    {
        writer.WriteLine(item.ToString("F9")); //note the F9
    }
};

9 is the amount of number you want to keep after decimal separator (.). You could specify the number as you want (for instance F10, F11, etc...)

like image 110
Ian Avatar answered Jun 02 '26 07:06

Ian


Save them as string instead for double;

using (StreamWriter writer = new StreamWriter(@"D:\Test.csv"))
{
    foreach (double item in arr)
    {
        writer.WriteLine(item.ToString("#.#########");
    }
};

For Formatting you can use any of the following:

"C", "E", "e", "F", "G", "N", "P", 
"R", "#,000.000", "0.###E-000",
"000,000,000,000.00###"
like image 28
sujith karivelil Avatar answered Jun 02 '26 07:06

sujith karivelil