【问题标题】:Ignore dots in Convert.ToDecimal and return 0忽略 Convert.ToDecimal 中的点并返回 0
【发布时间】:2022-01-17 11:51:05
【问题描述】:

我在 linq 中使用 Convert.ToDecimal,有时金额值会以点 (.) 的形式出现,因为用户可能想要写 .50 之类的东西,只要他们输入(使用来自移动设备的数字键盘) 值,代码被执行并抛出exception

下面的代码我收到string is not correct format exception

var enteredAmountInTenders = TenderListCollection.Sum(x => Convert.ToDecimal(string.IsNullOrEmpty(x.Amount) ? "0" : x.Amount));

我怎样才能忽略上面代码的点而只得到 0?

【问题讨论】:

  • 为什么它首先作为字符串到达​​ TenderListCollection,然后在使用数据时可能多次转换时遇到问题?听起来更合理的是已经在前端这样做了,之后只允许使用实数类型。
  • 拉尔夫怎么说。您将希望尽可能在叶子上进行字符串转换(即在输入之后/在显示之前)。

标签: c# string linq


【解决方案1】:

我会使用decimal.TryParse 而不是Convert.ToDecimal 来转换值。

var enteredAmountInTenders = TenderListCollection
               .Sum(x => !decimal.TryParse(x.Amount,out var result) ? 0 : result);

【讨论】:

    【解决方案2】:

    您可以在为 TenderListCollection 中的对象设置属性之前检查这一点。

    private string _amount = "0";
    
    public string Amount 
    {
       get 
       {
           return _amount;
       }
    
       set 
       {
           if(!string.IsNullOrEmpty(value))
           {
              if(value != ".")
              {
                  _amount = value;
              }
           }
       }
    }
    

    一般来说,我不喜欢将金额存储为字符串,所以我也建议将金额重命名为 GivenAmount 并拥有一个小数的金额属性,这样我们的代码很干净,您不需要解析Lambda 表达式。

    【讨论】:

    • 金额为十进制,问题是 - 它显示所有条目的默认值 0.00。我们不想展示它。我们只想显示空文本框。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-26
    • 2021-01-13
    • 2012-08-06
    • 1970-01-01
    相关资源
    最近更新 更多