繁体   English   中英

我该如何转换小数?到十进制

[英]How can I convert decimal? to decimal

可能是一个简单的问题,但我尝试了所有的转换方法! 它仍然有错误! 你能帮我吗?

十进制? (可以为十进制)到十进制

有很多选择......

decimal? x = ...

decimal a = (decimal)x; // works; throws if x was null
decimal b = x ?? 123M; // works; defaults to 123M if x was null
decimal c = x.Value; // works; throws if x was null
decimal d = x.GetValueOrDefault(); // works; defaults to 0M if x was null
decimal e = x.GetValueOrDefault(123M); // works; defaults to 123M if x was null
object o = x; // this is not the ideal usage!
decimal f = (decimal)o; // works; throws if x was null; boxes otherwise

尝试使用?? 运营商:

decimal? value=12;
decimal value2=value??0;

0是decimal?时想要的值decimal? 一片空白。

您无需转换可空类型即可获取其值。

您只需利用Nullable<T>公开的HasValueValue属性。

例如:

Decimal? largeValue = 5830.25M;

if (largeValue.HasValue)
{
    Console.WriteLine("The value of largeNumber is {0:C}.", largeValue.Value);
}
else
{
    Console.WriteLine("The value of largeNumber is not defined.");
}

或者,您可以使用C#2.0或更高版本中的空合并运算符作为快捷方式。

这取决于你想要做的decimal? null ,因为decimal不能为null 如果要将其默认为0,则可以使用此代码(使用空合并运算符 ):

decimal? nullabledecimal = 12;

decimal myDecimal = nullabledecimal ?? 0;

您可以使用。

decimal? v = 2;

decimal v2 = Convert.ToDecimal(v);

如果值为null(v),则将其转换为0。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM