c# - 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);
解决方案
如果你想要一个 null 来表示没有值,你可以使用一个可以为 null 的变量:
decimal? result = string.IsNullOrEmpty(price) ? null : decimal.Parse(price);
这比其他人提出的用零表示缺乏数据更好的选择。
在将结果用于某些目的之前,您可能必须检查结果是否为空。但是,支持通常的操作:
请参见null 的数学运算
推荐阅读
- windows - 如何修复我在 Windows 中遇到的这个 JMeter LoggerAppender 错误?
- python - Python:如何动态更新多个变量/字段
- scala - 如何在 Gatling 中创建基本的分页逻辑?
- java - 如何在 laravel 中返回 Content 类型?
- kotlin - 带有 Java 超类的 Kotlin 数据类
- c++ - GCC avx2intrin.h(版本 X-9.2)中缺少 _mm_broadcastsd_pd
- excel - excel SQL VBA更新2个访问表
- google-chrome - 从 Firebase 提供时,带有范围请求路由器的 Workbox 预缓存音频无法在 Chrome 中播放
- pyspark - 如何在 PySpark 中的两个日期之间生成每小时时间戳?
- javascript - Ajax POST 仅在页面刷新时执行 php 脚本