如何将小数转换为整型?
当前回答
没有答案似乎处理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
推荐文章
- 实体框架核心:在上一个操作完成之前,在此上下文中开始的第二个操作
- 如何为构造函数定制Visual Studio的私有字段生成快捷方式?
- 为什么Visual Studio 2015/2017/2019测试运行器没有发现我的xUnit v2测试
- 如何使用JSON确保字符串是有效的JSON。网
- AppSettings从.config文件中获取值
- 通过HttpClient向REST API发布一个空体
- 如何检查IEnumerable是否为空或空?
- 自动化invokerrequired代码模式
- 没有ListBox。SelectionMode="None",是否有其他方法禁用列表框中的选择?
- 在c#代码中设置WPF文本框的背景颜色
- 在c#中,什么是单子?
- c#和Java中的泛型有什么不同?和模板在c++ ?
- 如何舍入一个双到最近的Int在迅速?
- c#线程安全快速(est)计数器
- 如何将此foreach代码转换为Parallel.ForEach?