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

如何对DataGridView中带货币符号的格式化金额列完成求和计算

带货币符号的DataGridView金额列求和解决方案

方案1(优先选择):直接读取数据源原始值

UI层的格式化仅作用于显示逻辑,不建议直接基于显示字符串做计算。如果你的DataGridView绑定了DataTable、实体类集合等数据源,直接遍历数据源中的对应数值字段求和即可,完全不需要处理货币符号等格式内容。


方案2:基于单元格格式化字符串解析

如果确实无法直接获取数据源,只能读取单元格的显示值,可以使用decimal.Parse/decimal.TryParse的重载方法,指定货币解析规则和对应区域文化实现正确解析:

前提引用

using System.Globalization;

修正后求和代码

// 与你格式化金额时使用的文化保持一致
CultureInfo deCult = new CultureInfo("de-DE");
decimal sum = 0;

for (int i = 0; i < dataGridView1.Rows.Count; ++i)
{
    // 跳过DataGridView的新增空白行
    if (dataGridView1.Rows[i].IsNewRow) continue;
    object cellVal = dataGridView1.Rows[i].Cells[3].Value;
    if (cellVal == null || cellVal == DBNull.Value) continue;

    // 按货币规则解析,自动识别欧元符号、德式千分位/小数点规则
    if (decimal.TryParse(cellVal.ToString(), NumberStyles.Currency, deCult, out decimal currentAmt))
    {
        sum += currentAmt;
    }
}

关键参数说明

  • NumberStyles.Currency:指定解析规则适配货币格式,自动兼容货币符号、千分位分隔符、小数点等特征
  • 传入的CultureInfo必须和格式化金额时使用的文化完全一致,避免出现解析失败的情况

特殊情况优化

如果你的单元格仅显示时做了格式化,实际Value属性存储的仍是原始数值类型,可直接强转求和,性能最高且无解析风险:

decimal sum = 0;
for (int i = 0; i < dataGridView1.Rows.Count; ++i)
{
    if (dataGridView1.Rows[i].IsNewRow) continue;
    object cellVal = dataGridView1.Rows[i].Cells[3].Value;
    if (cellVal is decimal amt)
    {
        sum += amt;
    }
}

内容的提问来源于stack exchange,提问作者Aksel482

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 05:18:01