2014-05-09 32 views
-2

我正在創建POS(銷售點),並且在嘗試將價格「0.60」轉換爲整數時遇到問題。在C#中將包含句點(。)的字符串轉換爲Int32時的問題

數據背景:數據源的所有數據都來自MySQL數據庫,我已經設置並連接了沒有問題。

價格存儲在一個文本框中,並被格式化爲「0.60」,我相信這是它未被轉換的原因。我不斷收到下面的消息。

附加信息:輸入字符串格式不正確。

 //Puts the Price Into a String. 
     string NewPrice = txtPrice.Text; 

     //Converts The Quantity In the TextBox field to a numbers. 
     Quantity = Convert.ToInt32(txtQuant.Text); 

     //Incorrect Format & Attempt One. 
     //Price = Convert.ToInt32(NewPrice); <--- Problem. 
     //Price = int.Parse(NewPrice); 

     // I've also tried this method below with two '0' inside the { } brackets. 
     // But Still No Luck. 
     Price = Convert.ToInt32(string.Format("{0.00}",txtPrice.Text)); // <--- Problem. 

     // Times Price & Quantity to get Total Price (0.60 * 2 = 1.20) 
     TotalSingleItemPrice = Price * Quantity; 

     // The Single Item Price is added into the overall total. 
     TotalPrice += TotalSingleItemPrice; 

     // Converts Total Item Price to String from Int. 
     string TotalPriceStr = Convert.ToString(TotalSingleItemPrice);   

     // Puts TextBoxes/Strings Into One String array (I think). 
     string[] InizialItemList = new string[] { cmboInitItem.Text, Convert.ToString(Price), Convert.ToString(Quantity), TotalPriceStr}; 

     // Adds The String Array Into the Data Grid View. 
     DGVIIL.Rows.Add(InizialItemList); 

我試圖使用string.Format("{0.00}",txtPrice.Text)設置來解決這個問題,我看不出有什麼我都過來看了。如果可能,我希望價格出現在我的DataGridView - DGVIIL中,如0.60

+1

0.60不是整數... –

+0

一個整數,不能包含小數點,你應該轉換爲浮動或十進制 –

+0

@TMcKeown我知道這不是一個整數。有沒有合理的方法來解決這個問題?你可以用Float或Decimal做一個例子嗎?先謝謝了。 –

回答

3

0.60不是整數,錯誤是正確的

替代方案:

Decimal d = Decimal.Parse(txtPrice.Text); 

甚至更​​好:

Decimal d; 
if (decimal.TryParse(txtPrice.Text, out d) == false){ 
    //handle bad number... 
} 
+0

這是一個很好的答案,但用Decimal.TryParse()可能會更好。 –

+0

謝謝,建議採取。 –

+1

謝謝你,我剛剛使用了Decimal d,就像你說的那樣,它工作。現在我將按照Rick Davin的說法和Yuval Itzchakov的驗證原因添加TryParse()。 –

1

您需要使用decimal.ParseConvert.ToDecimal作爲字符串顯然不是int。在處理貨幣時推薦使用小數。

Price = Convert.ToDecimal(NewPrice); 
Price = decimal.Parse(NewPrice); 

另外,我建議你看看TryParse要用於驗證:

decimal price; 
if (decimal.TryParse(NewPrice, out price)) 
{ // do stuff } 
+0

處理貨幣時應該避免兩次? –

+0

如果您正在處理貨幣,請使用'decimal'。更新了我的答案 –

0
Price = Convert.ToInt32(string.Format("{0.00}",txtPrice.Text)); 
在你從一個小數樣式的格式轉換爲整數上面的代碼

。 int32類型只能包含整數,因此convert方法會給你一個錯誤。相反,您可以使用double類型來正確保存您的值。

double Price; 
Price = Convert.ToDouble(string.Format("{0.00}",txtPrice.Text)); 
1

您需要將其轉換爲double,然後轉換爲int。

int x = Convert.ToInt32(Convert.ToDouble("1.11")); 

//Expected output: x = 1 
相關問題