To force adding 0 need to use zero placeholder:
public class Foo
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime Time { get; set; }
public float Value1 { get; set; }
public double Value2 { get; set; }
}
var records = new List<Foo>
{
new Foo { Id = 1, Name = "one", Time = DateTime.Now, Value1 = 1.123f, Value2 = 12345.789 },
new Foo { Id = 2, Name = "two", Time = DateTime.Now, Value1 = 123f, Value2 = 44 },
};
var dt_options = new CsvHelper.TypeConversion.TypeConverterOptions {
Formats = new[] { "yyyy-MM-dd HH:mm" } };
var float_options = new CsvHelper.TypeConversion.TypeConverterOptions {
Formats = new[] { "###.0" } };
using (var writer = new StreamWriter("file.csv"))
using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
{
csv.Configuration.TypeConverterOptionsCache.AddOptions<DateTime>(dt_options);
csv.Configuration.TypeConverterOptionsCache.AddOptions<float>(float_options);
csv.Configuration.TypeConverterOptionsCache.AddOptions<double>(float_options);
csv.WriteRecords(records);
}
Id,Name,Time,Value1,Value2
1,one,2021-01-07 20:54,1.1,12345.8
2,two,2021-01-07 20:54,123.0,44.0
Configure CsvWriter if required to wrap all values to quotes:
..
using (var csv = new CsvWriter(writer,
new CsvConfiguration(CultureInfo.InvariantCulture) {
ShouldQuote = (_, _) => true }))
..
/*
"Id","Name","Time","Value1","Value2"
"1","one","2021-01-07 21:11","1.1","12345.8"
"2","two","2021-01-07 21:11","123.0","44.0"
*/
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…