首页 > 解决方案 > C# - 将字符串/空值转换为十进制

问题描述

我有一个方法和参数作为字符串或空值。所以我正在尝试将参数转换为十进制。我正在尝试使用decimal.Parse将字符串转换为十进制。

如果参数有一个空值不想转换为小数..

public void abcd(string price)
{
    decimal result = string.IsNullOrEmpty(price) ? null : decimal.Parse(price);
    //error - cannot convert null as decimal
    //I tried few other options also.
    decimal result = price is null ? 0 : decimal.Parse(price);
    // error - VAlue cannot be null

    //have other logic here
}

abcd("123");
abcd(null);

标签: c#

解决方案


如果你想要一个 null 来表示没有值,你可以使用一个可以为 null 的变量:

decimal? result = string.IsNullOrEmpty(price) ? null : decimal.Parse(price);

这比其他人提出的用零表示缺乏数据更好的选择。

在将结果用于某些目的之前,您可能必须检查结果是否为空。但是,支持通常的操作:

请参见null 的数学运算


推荐阅读