You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 10:45:47