将Object转换为int而不进行舍入

问题描述 投票:0回答:5

我必须将对象转换为int。我的对象值类似于1.34535我需要的是第一部分是(1)。

我尝试了以下方法: - Convert.ToInt32(myObj.Value),它将数字四舍五入。如果它是1.78,我得到它(2)这是错的。我只需要第一部分的整数。

  • int.TryParse(myObj.Value.toString(), out outValue)我得到了所有价值的0
  • int.Parse(myObj.Value.toString())抛出异常,格式不正确。
c# object int
5个回答
1
投票

如果myObj.Value装箱double然后你必须施放两次:取消装箱回到double然后为了截断到int

int result = (int)((double)(myObj.Value)):

一般情况下,试试qazxsw poi;这个想法是一样的:首先恢复原来的qazxsw poi,然后获得所需的Convert

double

编辑:在上面的实现中,我已经阅读了没有舍入请求的截断,即应忽略小数部分:

int

如果预期有不同的行为,例如

int result = (int) (Convert.ToDouble(myObj.Value));

一个人可以添加 2.4 -> 2 -2.4 -> -2 ,例如

 2.4 ->  2
-2.4 -> -3 

1
投票

首先转换为Math.Floor;

 int result = (int) (Math.Floor(Convert.ToDouble(myObj.Value)));

0
投票

将您的对象转换为double值并使用Use double

var doubleValue = double.Parse(myObj.Value.ToString()); //It could be better to use double.TryParse int myInt = (int)Math.Floor(doubleValue);


0
投票

很简单,别忘了将它包装在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


0
投票

也许,这也是一个解决方案:

-43.65445
© www.soinside.com 2019 - 2024. All rights reserved.