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

时间:2011-02-02 07:59:34

标签: c# .net decimal type-conversion nullable

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

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

5 个答案:

答案 0 :(得分:95)

有很多选择......

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

答案 1 :(得分:25)

尝试使用??运算符:

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

0是decimal?为空时所需的值。

答案 2 :(得分:10)

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

您只需利用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或更高版本中的null coalescing operator作为快捷方式。

答案 3 :(得分:3)

如果decimal?null,则取决于您要执行的操作,因为decimal不能为null。如果要将其默认为0,则可以使用此代码(使用 null合并运算符):

decimal? nullabledecimal = 12;

decimal myDecimal = nullabledecimal ?? 0;

答案 4 :(得分:-2)

你可以使用。

decimal? v = 2;

decimal v2 = Convert.ToDecimal(v);

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

相关问题