我该如何将十进制转换为整数?
似乎没有回答如何处理OverflowException/UnderflowException,这是由于尝试将超出int范围的十进制数转换而引起的。
int intValue = (int)Math.Max(int.MinValue, Math.Min(int.MaxValue, decimalValue));
如果十进制值超出int范围,此解决方案将返回最大或最小的int值。如果值在int范围内,则可能需要使用Math.Round、Math.Ceiling或Math.Floor进行四舍五入。
将十进制转换为整数
decimal decimalValue=5.00;
int intValue=Convert.ToInt32(decimalValue);
SqlCommand foo = new SqlCommand("INSERT INTO...; SELECT SCOPE_IDENTITY()", conn);
int ID = Convert.ToInt32(foo.ExecuteScalar()); // works
int ID = (int)foo.ExecuteScalar(); // throws InvalidCastException
请参见4.3.2 拆箱转换
SELECT SCOPE_IDENTITY()
返回numeric(38, 0)
,它被.NET翻译为decimal
。foo.ExecuteScalar()
返回一个作为object
装箱的decimal
,不能直接转换为int
。(int)(decimal)foo.ExecuteScalar()
或Convert.ToInt32(foo.ExecuteScalar())
可以工作。 - rageit