![](/img/trans.png)
[英]Why float is bigger than double after computing same value? Why float can't be implicitly converted to Decimal
[英]how throw exception if decimal value is bigger than float in C#
如果小数的值大于浮点数(无浮点数),我想抛出异常
下面的此示例代码可以很好地工作(throwoverflowException)对于整数
decimal a = decimal.MaxValue;
int b = checked(int.Parse(a.ToString()));
但是此示例代码不会引发任何异常
decimal a = decimal.MaxValue;
float b = checked(float.Parse(a.ToString())); // b is 7.92281625E+28
如何确定小数的值是否大于浮点数(无浮点数)?
int b = checked(int.Parse(a.ToString()));
检查值是否会导致OverflowException
一种非常糟糕的方法,因为您不知道a
将如何表示为字符串。
而是使用强制转换 :
decimal d = decimal.MaxValue;
int i = (int)d;
// Throws OverflowException
正如@Enigmativity和@CodeCaster在注释中指出的那样, decimal
的整数部分始终适合于float
:
decimal d = decimal.MaxValue;
float i = (float)d;
// No problem!
您可以使用decimal.Truncate如果你只需要删除的小数部分decimal
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.