2017-12-18 183 views
0

我必須將對象轉換爲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())引發異常,即格式不正確。

+0

如果什麼值是13.4535,你仍然需要只是「1」的一部分或「13」? –

+1

該對象的源類型是什麼? –

+6

什麼是*對象?將在自然類型的輸入中調用'Math.Floor',然後*轉換爲int:work? –

回答

1

如果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))); 
+0

我認爲,該解決方案不適用於負數。 (int)((double)( - 2.4))將爲-2。 – lucky

+0

@Rainman:好的,這個問題並沒有說明*負數*應該做什麼。我建議*截斷*:'2.42 - > 2','-2.4 - > -2'(小數部分*忽略)。如果它不是所需的行爲('-2.4'應該放在'-3'中)'Math.Floor'可以被添加:'(int)(Math.Floor(Convert.ToDouble(myObj.Value)));' –

+0

在我看來,OP希望少一個雙數。無論如何,OP應該做出決定。 – lucky

1

它首先轉換爲double;

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

它會圍繞少一個。 Math.Floor(-2.4)是-3。 – lucky

+0

這個答案是不正確的,它不適用於負數 – Alander

+0

「它不適用於負數」這是什麼意思?如果你想將數字舍入到少一個,使用「Floor」,如果你想採取第一部分只使用「截斷」。這取決於要求。 – lucky

0

很容易,不要忘了將它包裝在trycatch

int i = (int)Math.Truncate(double.Parse(myObj.ToString())); 

Math.Truncate只需切斷逗號後的數字即可:

4.434成爲4

-43.65445成爲-43

0

或許,這也是一個解決方案:

var integer = int.Parse(myObject.Value.ToString().Split('.').First());