Home > database >  Double values get converted to string values when the double values has decimal points
Double values get converted to string values when the double values has decimal points

Time:04-26

I am trying to use CSVHelper library to write data into a MemoryStream and then generate a CSV file using that MemoryStream.

The problem is Double values get converted to weird string values when the double values have decimal points. The expected output and weird output are there at the bottom.

Is anyone know how to overcome this issue? or Is there any mistake in the below code?

public class Foo
{
    public Foo()
    {
    }

    public double valOne { get; set; }

    public double valTwo { get; set; }
}

public class FooMap : ClassMap<Foo>
{
    public FooMap()
    {
        Map(m => m.valOne).Index(0).Name("Val One");
        Map(m => m.valTwo).Index(1).Name("Val Two");
    }
}

var records = new List<Foo> {
    new Foo{valOne = 3224.12, valTwo = 4122},
    new Foo{valOne = 2030.20, valTwo = 5555},
};

var config = new CsvConfiguration(CultureInfo.CurrentCulture) { Delimiter = ",", HasHeaderRecord = true };

using (var memoryStream = new MemoryStream())
using (var writer = new StreamWriter(memoryStream))
using (var csv = new CsvWriter(writer, config))
{
    csv.Context.RegisterClassMap<FooMap>();

    csv.WriteHeader<Foo>();

    csv.NextRecord();
    foreach (var record in records)
    {
        csv.WriteRecord(record);
        csv.NextRecord();
    }

    writer.Flush();
    
    var result = Encoding.UTF8.GetString(memoryStream.ToArray());

    byte[] bytes = Encoding.ASCII.GetBytes(result);

    return new FileContentResult(bytes, "text/csv")
    {
        FileDownloadName = "Sample_Report_Name"
    };
}

Expected Output:

Val One, Val Two
3224.12,4122
2030.20,5555

Weird Output:

Val One, Val Two
"3224,12",4122
"2030,20",5555

CodePudding user response:

The issue is the CurrentCulture of the computer running the code uses commas instead of periods to indicate the decimal point. Using CultureInfo.InvariantCulture instead of CultureInfo.CurrentCulture should fix the formatting issue.

Also, you can simplify your code by using csv.WriteRecords(records).

var records = new List<Foo> {
    new Foo{valOne = 3224.12, valTwo = 4122},
    new Foo{valOne = 2030.20, valTwo = 5555},
};

var config = new CsvConfiguration(CultureInfo.CurrentCulture) { Delimiter = ",", HasHeaderRecord = true };

using (var memoryStream = new MemoryStream())
using (var writer = new StreamWriter(memoryStream))
using (var csv = new CsvWriter(writer, config))
{
    csv.Context.RegisterClassMap<FooMap>();

    csv.WriteRecords(records);

    writer.Flush();
    
    var result = Encoding.UTF8.GetString(memoryStream.ToArray());

    byte[] bytes = Encoding.ASCII.GetBytes(result);

    return new FileContentResult(bytes, "text/csv")
    {
        FileDownloadName = "Sample_Report_Name"
    };
}
  • Related