Subru
Subru

Reputation: 353

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.

Upvotes: 3

Views: 3977

Answers (4)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186823

If you want to represent a value in some special format (e.g. with leading zeros) use formatting: String.Format(). You have no need in StreamWriter: put File.WriteAllLines and let .Net do the work for you:

  File.WriteAllLines(@"D:\Test.csv", 
    arr.Select(item => item.ToString("F9", CultureInfo.InvariantCulture)));

Upvotes: 1

Marco Bong
Marco Bong

Reputation: 690

enter image description here

you just need to expand the column width (double click the line between A & B).

Upvotes: 0

sujith karivelil
sujith karivelil

Reputation: 29036

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###"

Upvotes: 2

Ian
Ian

Reputation: 30813

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...)

Upvotes: 6

Related Questions