0

Hi guys i'd like to write random double into a csv file ,for now am inserting string into the row, here is what i've done.How can alter my code in order to write doubles instead of string Many thanks in advance

public class CsvRow : List<string>
{
    public string LineText { get; set; }
}
/// <summary>
/// Class to write data to a CSV file
/// </summary>
public class CsvFileWriter : StreamWriter
{
    public CsvFileWriter(Stream stream)
        : base(stream)
    {
    }

    public CsvFileWriter(string filename)
        : base(filename)
    {
    }
    /// <summary>
    /// Writes a single row to a CSV file.
    /// </summary>
    /// <param name="row">The row to be written</param>
    public void WriteRow(CsvRow row)
    {
        StringBuilder builder = new StringBuilder();
        bool firstColumn = true;
        foreach (string value in row)
        {
            // Add separator if this isn't the first value
            if (!firstColumn)
                builder.Append(',');
            // Implement special handling for values that contain comma or quote
            // Enclose in quotes and double up any double quotes
            if (value.IndexOfAny(new char[] { '"', ',' }) != -1)
                builder.AppendFormat("\"{0}\"", value.Replace("\"", "\"\""));
            else
                builder.Append(value);
            firstColumn = false;
        }
        row.LineText = builder.ToString();
        WriteLine(row.LineText);
    }
}      static void WriteTest()
    {

        // Write sample data to CSV file
        using (CsvFileWriter writer = new CsvFileWriter("D://WriteTest.csv"))   CsvRow rowCol = new CsvRow();
            for (int j = 0; j < nbrCol; j++)

               rowCol.Add("Col" +j);

            writer.WriteRow(rowCol);
        {
            for (int i = 0; i < 100; i++)
            {
                CsvRow row = new CsvRow();
                for (int j = 0; j < 5; j++)
                    row.Add(String.Format("Column{0}", j));

                writer.WriteRow(row);
            }
        }
    }
2
  • 2
    Sorry for not getting this, but can you display the current output and your desired output for easier understanding? Commented Jan 4, 2017 at 8:09
  • , actually am writing radom double in a csv file .it means i wanna have for example 4 column , 20 rows containing all double seperated with ",".I made a first draft in wich i got this in csv file Column0,Column1,Column2,Column3,Column4 Column0,Column1,Column2,Column3,Column4 Column0,Column1,Column2,Column3,Column4 Column0,Column1,Column2,Column3,Column4 Column0,Column1,Column2,Column3,Column4 Column0,Column1,Column2,Column3,Column4 Column0,Column1,Column2,Column3,Column4 , how can modify my code to get random double instead of column0,column 1 ....... thnx for your help Commented Jan 4, 2017 at 8:15

1 Answer 1

2

simply this:

    static void WriteTest()
    {
        // Write sample data to CSV file
        using (CsvFileWriter writer = new CsvFileWriter(@"E:\SharedDoc1\WriteTest.csv"))
        {
            Random rnd = new Random();

            for (int i = 0; i < 100; i++)
            {
                CsvRow row = new CsvRow();
                for (int j = 0; j < 5; j++)
                    row.Add(rnd.NextDouble().ToString("0.000000")); //round to 6 decimal digits

                writer.WriteRow(row);
            }
        }
    }

the output is as following:

0.848731,0.525468,0.829536,0.397083,0.493102 0.398665,0.914157,0.768229,0.520031,0.249966 0.083535,0.409240,0.325824,0.177057,0.114989

Note that rnd.NextDouble() returns a double between 0 and 1, if you want larger numbers you should multiply it with your factor. For example if you want doubles up to 1000 do this:

row.Add((rnd.NextDouble() * 1000).ToString("0.0#####"));
Sign up to request clarification or add additional context in comments.

9 Comments

Am very thankfull just one last request ,the line for example i got "0,306837749810348" , how the code will if i would like to find something like this 0.306837749810348 itt means remove the " " and replace the "," with a " ." thnx
i do not if you get my point , i got something like "0,199667","0,820243" but what i want to get is 0.199667,0.820243 I want to use the . for the double and to remove " " thnx
i'm not sure why you get those extra quotation marks "", they should not be present. but it seems that your current culture/language is other than normal English language... can you try: row.Add(rnd.NextDouble().ToString("0.0#####",System.Globalization.CultureInfo.InvariantCulture));
@waynemodz its execution performance is lower as the ToString method will produce some string and then do another search for replacing...
@S.serp i just realized that as u commented
|

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.