如何将小数转换为整型?


当前回答

没有答案似乎处理OverflowException/UnderflowException来自试图转换int范围之外的小数。

int intValue = (int)Math.Max(int.MinValue, Math.Min(int.MaxValue, decimalValue));

如果十进制值在int范围之外,此解决方案将返回可能的最大或最小int值。你可能想用Math添加一些舍入。圆的,数学。天花板或数学。当值在int范围内时的下限。

其他回答

没有答案似乎处理OverflowException/UnderflowException来自试图转换int范围之外的小数。

int intValue = (int)Math.Max(int.MinValue, Math.Min(int.MaxValue, decimalValue));

如果十进制值在int范围之外,此解决方案将返回可能的最大或最小int值。你可能想用Math添加一些舍入。圆的,数学。天花板或数学。当值在int范围内时的下限。

我发现强制转换操作符不工作,如果你有一个盒装小数(即一个对象类型内的十进制值)。转换。ToInt32(作为对象的十进制)在这种情况下工作正常。

当从数据库中检索IDENTITY/ autoumber值时出现这种情况:

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开箱转换

将十进制转换为整数

decimal decimalValue=5.00;
int intValue=Convert.ToInt32(decimalValue);

系统。Decimal实现了IConvertable接口,该接口有一个ToInt32()成员。

调用System.Decimal.ToInt32()工作吗?

decimal vIn = 0.0M;
int vOut = Convert.ToInt32(vIn);

这是一个非常方便的转换数据类型的网页,为那些其他人。 http://www.convertdatatypes.com/Convert-decimal-to-int-in-CSharp.html