35
A
回答
3
這取決於你想要如果decimal?
做的是null
,因爲decimal
不能null
。如果你想默認是0,你可以使用此代碼(使用空合併運算符):
decimal? nullabledecimal = 12;
decimal myDecimal = nullabledecimal ?? 0;
22
嘗試使用??
操作:
decimal? value=12;
decimal value2=value??0;
0是你想要的值當decimal?
爲空時。
10
您不需要將轉換爲可以爲空的類型以獲取其值。
您只需利用Nullable<T>
公開的HasValue
和Value
屬性。
例如:
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.");
}
或者,也可以使用在null coalescing operator C#2.0或更高作爲快捷方式。
-2
您可以使用。
decimal? v = 2;
decimal v2 = Convert.ToDecimal(v);
如果值爲null(V),它將被轉換爲0
79
有大量的選項...
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
+1。我更喜歡'GetValueOrDefault`,因爲它不依賴於C#語法,因此也可以在VB.NET中使用。如果該類型的默認值不適用於您,它也很容易調整。 – Neolisk 2014-04-15 18:50:05
相關問題
- 1. 如何將十進制小數轉換爲十六進制小數?
- 2. C++將八進制小數轉換爲十進制小數?
- 3. 轉換爲小數?原始十進制
- 4. 如何將十六進制NSData轉換爲十進制數組?
- 5. 十進制數字轉換
- 6. 轉換爲十進制數
- 7. 十六進制和十進制轉換
- 8. 轉換十六進制到十進制
- 9. 十進制轉換
- 10. 如何在PHP中將小數值轉換爲十進制值
- 11. 將八進制數轉換爲十進制和十六進制
- 12. 轉換十進制值小時和分鐘,並以小時
- 13. 如何轉換OCaml中十六進制,十進制,十進制和二進制數之間的數字?
- 14. 如何將十六進制字符串轉換爲十進制?
- 15. 如何將14位十六進制轉換爲十進制
- 16. 如何在bash中將十進制轉換爲十六進制?
- 17. 如何十六進制轉換爲十六進制
- 18. 如何負十六進制轉換爲十進制
- 19. 如何將負十進制轉換爲十六進制?
- 20. 如何在Python中將十六進制轉換爲十進制?
- 21. 將十進制轉換爲十六進制和十六進制
- 22. 十六進制轉換爲十進制電壓轉換
- 23. 十進制轉換爲十六進制的轉換(Java)的
- 24. 將非十進制數轉換爲十進制數
- 25. 如何在VIM中將十進制數轉換爲十六進制數?
- 26. 在Scala中將十進制小數轉換成二進制小數
- 27. 如何將數字(十進制)轉換爲二進制(二進制)數字和從二進制到十進制?
- 28. 如何將int數從十進制轉換爲二進制
- 29. 如何將二進制轉換爲十進制與長整數?
- 30. 轉換32位二進制數轉換爲十進制
我認爲Convert.ToDecimal()是字符串表示,不用於將可空的十進制轉換爲十進制。請參閱此處:https://msdn.microsoft.com/en-us/library/9k6z9cdw(v=vs.110).aspx – 2016-02-16 16:17:08