2017-04-04 66 views
0

這應該是一個簡單的代碼:爲什麼Convert.ToInt32或Int32.Parse不適合我?

 string qty = "211.0000"; 
     Console.WriteLine(Int32.Parse(qty)); 

我試圖用Convert.ToInt32Int32.Parse,但他們都拋出一個錯誤: 錯誤(S): 異常的用戶代碼:

System.FormatException: Input string was not in a correct format.
at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal)
at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info) at Rextester.Program.Main(String[] args)

我是否犯過錯誤來定義一個字符串並給出一個值?我曾嘗試使用stringString來定義變量。它適用於我使用Console.WriteLine(Convert.ToInt32("211.0000"))

BTW我http://rextester.com/

+5

' 「211.0000」'不是有效的*整數*值,而是*浮點* 1。 –

+0

因爲它不是一個整數 –

+0

@Dmitry Bychenko但我想通過使用雙引號將它定義爲一個字符串,然後將其轉換爲int。至少Convert.ToInt32應該工作是不是? –

回答

4

工作浮點值(有明確的小數分隔.)你應該使用decimaldouble

using System.Globalization; 

    ... 

    string qty = "211.0000"; 

    // be careful: different cultures have different decimal separators 
    decimal result = decimal.Parse(qty, CultureInfo.InvariantCulture); 

double result = double.Parse(qty, CultureInfo.InvariantCulture); 

已經得到了浮點表示你能讓它爲整數

int value = (int) (result > 0 ? result + 0.5 : result - 0.5); 

int value = (int) (Math.Round(result)); 
+0

哇不知道這是非常棘手在C#中將雙精度字符串轉換爲整數... –

+0

爲什麼不直接調用'Math.Round'? – hvd

+0

@hvd:對不起,從純'C'的壞習慣... –

0

是測試你需要使用Decimal代替int

Decimal.Parse(qty); 

如果你只需要那麼整數部分使用下面的代碼片段

Double.Parse(qty, CultureInfo.InvariantCulture); 
+0

它給了我2110000,但我想要211 ... –

+0

剛編輯我的答案,它會給你預期的結果。 – Sameer

+0

仍然2110000 ... –

0

值你提供的不是一個整數,在你可能嘗試的所有東西都將它轉換爲小數之後,並在使用之後Convert.ToInt32mscorlib因爲整數不能包含小數點,洙這意味着你不能解析它作爲一個Int32,請按照下面的例子:

string value = String.Format("{0:0.00}", 123.4567);  // "123.46" 
decimal d = decimal.Parse(value); 
Convert.ToInt32(d); 
+0

它給了我2110000,但我想要211 –

+0

@JamesChen檢查編輯 –

+0

@JamesChen如果你沒有指定文化信息('IFormatProvider'),將使用當前的文件信息。在'rextester.com'上將會是_German(德國)_。因此,如果您想要小數點分隔符,則需要使用逗號。所以'decimal.Parse(「211,0000」)'會給這個文化帶來'211',而'decimal.Parse(「211.0000」)'給出'2110000'。 –

1

我改變了我的答案,希望這是確定的,但這裏可能是最好的事情對你來說是做一個decimal.TryParse,它可以處理前導字符,如-.,然後將結果轉換爲一個整數。

decimal result; 
Console.WriteLine(decimal.TryParse(qty, NumberStyles.Any, 
    CultureInfo.InvariantCulture, out result) ? (int)result : 0); 

相同的代碼可以用來存儲INT供以後使用:如果解析失敗,它(其中字符串不是一個小數的情況下)返回一個零

decimal result; 
int intResult = decimal.TryParse(qty, NumberStyles.Any, 
    CultureInfo.InvariantCulture, out result) ? (int) result : 0; 
+0

有點奇怪,但計數器的例子:'「.123」'預計輸出'0',實際 - 異常 –

+0

正如我所說,你需要有一個'。'前面的有效整數字符。 –

+1

已更新答案,以填充字符串的示例爲前綴'0',以便小數點開始 –