使用C# CSVHelper写入CSV时保留Decimal类型两位小数的问题
解决CsvHelper保留Decimal类型两位小数的问题
你的问题核心是配置错了类型——你给double?加了格式规则,但实体里的CurrentPrice、FuturePrice、MinQty都是decimal类型,所以之前的配置根本没生效。
下面给两种可行的修改方案:
方案一:全局配置Decimal类型的转换规则
直接在TypeConverterOptionsCache里给decimal类型设置格式,覆盖所有该类型的字段:
CsvConfiguration config = new CsvConfiguration(CultureInfo.InvariantCulture); config.ShouldQuote = args => true; using (var writer = new StreamWriter("..\\..\\..\\CSVs\\test.csv")) using (var csv = new CsvWriter(writer, config)) { // 给decimal类型设置两位小数格式 csv.Context.TypeConverterOptionsCache.AddOptions<decimal>(new TypeConverterOptions { Formats = new string[] { "F2" }, // "F2"表示固定两位小数 NumberStyles = NumberStyles.AllowDecimalPoint }); csv.WriteRecords(customerPrices); }
方案二:给单个字段加特性(更灵活)
如果只想给特定的decimal字段设置格式,可以在实体属性上直接加[Format]特性:
public class CustomerPrice { public string? PriceStatus { get; set; } public string? BGRItem { get; set; } public string? CustomerNumber { get; set; } public string? Description { get; set; } public string? Category { get; set; } [Format("F2")] // 给CurrentPrice设置两位小数 public decimal CurrentPrice { get; set; } [Format("F2")] // 给FuturePrice设置两位小数 public decimal FuturePrice { get; set; } public string? UOM { get; set; } [Format("F2")] // 给MinQty设置两位小数 public decimal MinQty { get; set; } [Format("MM/dd/yyyy")] public DateTime Effective { get; set; } [Format("MM/dd/yyyy")] public DateTime LastSale { get; set; } }
修改后生成的CSV里,decimal字段会固定显示两位小数,比如原来的10.0000会变成10.00,1.00保持1.00。
内容的提问来源于stack exchange,提问作者Andrew Biddle
相关产品推荐
相关产品推荐

