繁体   English   中英

如果C#中的十进制值大于float,则如何引发异常

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM