将对象转换为int而不舍入
我必须将对象转换为int。我的对象值类似于1.34535 我需要的是第一部分是(1)。将对象转换为int而不舍入
我尝试了以下方法: - Convert.ToInt32(myObj.Value),它将数字四舍五入。如果它是1.78,我知道了(2)这是错误的。我只需要第一部分的整数。
int.TryParse(myObj.Value.toString(), out outValue)我得到了它0所有值!int.Parse(myObj.Value.toString())引发异常,即格式不正确。
回答:
如果myObj.Value是盒装double,那么你必须投两次:到拆箱回double,然后以截断成int:
int result = (int)((double)(myObj.Value)): 在一般情况下,请尝试Convert;这个想法是一样的:先还原一部开拓创新double,然后获取所需int:
int result = (int) (Convert.ToDouble(myObj.Value)); 编辑:在执行上面的我读过没有四舍五入请求作为截断,即小数部分应被忽略:
2.4 -> 2 -2.4 -> -2
如果不同是正常现象,如
2.4 -> 2 -2.4 -> -3
可以添加Math.Floor例如,
int result = (int) (Math.Floor(Convert.ToDouble(myObj.Value))); 回答:
它首先转换为double;
var doubleValue = double.Parse(myObj.Value.ToString()); //It could be better to use double.TryParse
int myInt = (int)Math.Floor(doubleValue);
回答:
转换你的对象为double值,并使用使用Math.Truncate(number)
http://msdn.microsoft.com/en-us/library/c2eabd70.aspx
回答:
很容易,不要忘了将它包装在try和catch:
int i = (int)Math.Truncate(double.Parse(myObj.ToString())); Math.Truncate只需切断逗号后的数字即可:
4.434成为4
-43.65445成为-43
回答:
或许,这也是一个解决方案:
var integer = int.Parse(myObject.Value.ToString().Split('.').First()); 以上是 将对象转换为int而不舍入 的全部内容, 来源链接: utcz.com/qa/262535.html

