![](/img/trans.png)
[英]Why float is bigger than double after computing same value? Why float can't be implicitly converted to Decimal
[英]What is the minimum decimal which can be converted to float and then back to decimal?
var t = (decimal)((float)decimal.MinValue)
失败并error CS0031: Constant value '-7.922816E+28' cannot be converted to a 'decimal'
,但为什么呢?
decimal.MinValue
是-79228162514264337593543950335m
。 它成功转换为float
为-79228160000000000000000000000f
,它大于decimal.MinValue
:
(float)decimal.MinValue > decimal.MinValue
为什么这个值不能转换? 我知道这与有效数和指数有关,但到底发生了什么? 在 C# 中,哪个是可以转换为浮点数然后返回十进制的最小十进制数?
您没有打印浮点数的完整精度,因此您看不到导致它失败的值。
如果您将代码更改如下:
var decMin = (float)decimal.MinValue;
Console.WriteLine(decMin.ToString("R")); // "-7.9228163E+28"
// Next line throws System.OverflowException: Value was either too large or too small for a Decimal.
var dec = (decimal)decMin;
decMin
的值显示为-7.9228163E+28
。 为了更容易比较,让我们在没有指数的情况下重写它并将其与decimal.MinValue
进行比较:
decMin = -79_228_163_000_000_000_000_000_000_000
decimal.MinValue = -79_228_162_514_264_337_593_543_950_335
现在您可以看到decMin
比decimal.MinValue
更负 - 这解释了为什么它无法转换。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.