如果我嘗試從Decimal
轉換Decimal.MaxValue
到Single
,然後再返回,轉換失敗有OverflowException
:爲什麼Decimal.MaxValue不會在Single和Decimal之間轉換?
Convert.ToDecimal(Convert.ToSingle(Decimal.MaxValue))
// '...' threw an exception of type 'System.OverflowException'
// base: {"Value was either too large or too small for a Decimal."}
是怎麼回事?當然值Decimal.MaxValue
作爲Single
應該是一個有效的Decimal
值?
我明白Single
和Decimal
之間的差異期望的精度從Decimal
轉換損失Single
但Single.MaxValue
大於Decimal.MaxValue
它沒有意義的「價值是太大或太小十進制「。如果您認爲這樣做有道理,請解釋答案中的原因。
此外,
Convert.ToSingle(Decimal.MaxValue)
// 7.92281625E+28
所以沒有問題這個號碼轉換爲Single
。
你是否會混淆'double'和'decimal'? 'Decimal.MaxValue'爲79,228,162,514,264,337,593,543,950,335,'Single.MaxValue'爲3.402823e38。 – kat0r
@DStanley不,它不是。 'var s = Convert.ToSingle(Decimal.MaxValue);'運行得很好。 – juharr
請注意,'float'只會有十進制值的近似值,看起來近似值更大。 – juharr