如何将小数转换为整型?


当前回答

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

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

其他回答

我发现强制转换操作符不工作,如果你有一个盒装小数(即一个对象类型内的十进制值)。转换。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开箱转换

使用转换。从mscorlib中的ToInt32

decimal value = 3.14m;
int n = Convert.ToInt32(value);

看到MSDN。你也可以使用Decimal.ToInt32。同样,请参见MSDN。最后,你可以直接转换为

decimal value = 3.14m;
int n = (int) value;

它使用显式强制转换操作符。看到MSDN。

快速舍入的一个巧妙技巧是在将小数点转换为整型之前加上。5。

decimal d = 10.1m;
d += .5m;
int i = (int)d;

仍然保留i=10,但是

decimal d = 10.5m;
d += .5m;
int i = (int)d;

四舍五入,使i=11。

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

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

decimal d = 2;
int i = (int) d;

这应该可以正常工作。