当双精度值具有小数点时,双精度值将转换为字符串值

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

我正在尝试使用 CSVHelper 库将数据写入 MemoryStream,然后使用该 MemoryStream 生成 CSV 文件。

问题是当双精度值有小数点时,双精度值会转换为奇怪的字符串值。底部有预期的输出和奇怪的输出。

有人知道如何解决这个问题吗?或者下面的代码有没有错误?

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

问题是计算机的 CurrentCulture 运行 代码使用逗号而不是句点来指示小数点。使用 CultureInfo.InvariantCulture 而不是 CultureInfo.CurrentCulture 应该可以解决格式问题。

此外,您可以使用 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"
    };
}